<?php
namespace App\Api\Controllers\Wallet;


use App\Api\Controllers\BaseController;
use App\Common\UserGetMoney;
use App\Models\ActivityStoreRate;
use App\Models\Merchant;
use App\Models\MerchantAccount;
use App\Models\MerchantStore;
use App\Models\MerchantWalletDayCount;
use App\Models\MerchantWalletDetail;
use App\Models\MerchantWithdrawalsRecords;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\SettlementConfig;
use App\Models\SettlementList;
use App\Models\SettlementListInfo;
use App\Models\Store;
use App\Models\User;
use App\Models\UserAccount;
use App\Models\UserWalletDetail;
use App\Models\UserWithdrawalsRecords;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class SelectController extends BaseController
{

    //返佣类型
    public function source_type(Request $request)
    {
        try {
            $public = $this->parseToken();

            if ($public->type == "merchant") {
                $user_id = $public->merchant_id;
                //  $user = Merchant::where('id', $user_id)->first();
            }

            if ($public->type == "user") {
                $user_id = $public->user_id;
                //  $user = User::where('id', $user_id)->first();
            }

            $data = [
                [
                    'source_type' => '12000',
                    'source_desc' => 'TF传化',
                ],
                [
                    'source_type' => 'hb',
                    'source_desc' => '红包码',
                ],
                [
                    'source_type' => '3000',
                    'source_desc' => '快钱支付',
                ],
                [
                    'source_type' => '1000',
                    'source_desc' => '支付宝',
                ],
                [
                    'source_type' => '2000',
                    'source_desc' => '微信支付',
                ],
                [
                    'source_type' => '6000',
                    'source_desc' => '京东金融',
                ],
                [
                    'source_type' => '8000',
                    'source_desc' => '新大陆',
                ],
                [
                    'source_type' => '9000',
                    'source_desc' => '和融通',
                ],
                [
                    'source_type' => '15000',
                    'source_desc' => '哆啦宝',
                ], 
		[
                    'source_type' => '13000',
                    'source_desc' => '随行付',
                ], 
		[
                    'source_type' => '19000',
                    'source_desc' => '随行付A',
                ], 
		[
                    'source_type' => '16000',
                    'source_desc' => '支付宝-ZFT',
                ], 
		[
                    'source_type' => '16001',
                    'source_desc' => '花呗分期-ZFT',
                ], 
		[
                    'source_type' => '1001',
                    'source_desc' => '花呗分期',
                ], 
		[
                    'source_type' => '23000',
                    'source_desc' => 'HL葫芦',
                ]
            ];

            $this->status = 1;
            $this->message = '数据返回成功';
	    
            return $this->format($data);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }


    //返佣列表
    public function source_query(Request $request)
    {
        try {
            $public = $this->parseToken();
            $source_type = $request->get('source_type', '');
            $settlement = $request->get('settlement', '');
            $time_start = $request->get('time_start', date("Y-m-d 00:00:00", time()));
            $time_end = $request->get('time_end', date("Y-m-d H:i:s", time()));
            $return_type = $request->get('return_type', '');
            $user_id = $request->get('user_id', '');
            $out_trade_no = $request->get('out_trade_no', '');
            $store_id = $request->get('store_id', '');

            $data = [];
            $where = [];
            //限制时间
            $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
            $day = 31;
            if ($date > $day) {
                return json_encode([
                    'status' => 2,
                    'message' => '时间筛选不能超过' . $day . '天'
                ]);
            }

            if ($source_type) {
                $where[] = ['source_type', '=', $source_type];
            }

            if ($settlement) {
                $where[] = ['settlement', '=', $settlement];
            }

            if ($public->type == "merchant") {
                $user_id = $public->merchant_id;
                $where[] = ['merchant_id', '=', $user_id];

                if ($time_start) {
                    $where[] = ['created_at', '>=', $time_start];
                }

                if ($time_end) {
                    $where[] = ['created_at', '<=', $time_end];
                }

                if ($store_id) {
                    $where[] = ['store_id', '=', $store_id];
                }

                $merchant = Merchant::where('id', $user_id)
                    ->select('money', 'settlement_money', 'unsettlement_money')
                    ->first();
                $money = $merchant->money;

                $table = 'merchant_wallet_details' . '_' . date('Ymd', strtotime($time_start));
                if (env('DB_D1_HOST')) {
                    if (Schema::hasTable($table)) {
                        $merchant_wallet_details = DB::connection("mysql_d1")->table($table);
                    } else {
                        $merchant_wallet_details = DB::connection("mysql_d1")->table("merchant_wallet_details");
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $merchant_wallet_details = DB::table($table);
                    } else {
                        $merchant_wallet_details = DB::table('merchant_wallet_details');
                    }
                }

                if (env('DB_D1_HOST')) {
                    if (Schema::hasTable($table)) {
                        $merchant_wallet_details1 = DB::connection("mysql_d1")->table($table);
                    } else {
                        $merchant_wallet_details1 = DB::connection("mysql_d1")->table("merchant_wallet_details");
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $merchant_wallet_details1 = DB::table($table);
                    } else {
                        $merchant_wallet_details1 = DB::table('merchant_wallet_details');
                    }
                }

                if (env('DB_D1_HOST')) {
                    if (Schema::hasTable($table)) {
                        $merchant_wallet_details2 = DB::connection("mysql_d1")->table($table);
                    } else {
                        $merchant_wallet_details2 = DB::connection("mysql_d1")->table("merchant_wallet_details");
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $merchant_wallet_details2 = DB::table($table);
                    } else {
                        $merchant_wallet_details2 = DB::table('merchant_wallet_details');
                    }
                }

                //返佣金额
                $settlement_money_where = $where;
                $settlement_money_where[] = ['settlement', '=', '01'];
                $unsettlement_money_where = $where;
                $unsettlement_money_where[] = ['settlement', '=', '02'];
                $settlement_money = $merchant_wallet_details->where($settlement_money_where)->select('money')->sum('money');
                $unsettlement_money = $merchant_wallet_details1->where($unsettlement_money_where)->select('money')->sum('money');

                $detail = $merchant_wallet_details2->where($where);
            }

            if ($public->type == "user") {
                //不允许跨天操作
                $time_start_db = date('Ymd', strtotime($time_start));
                $time_end_db = date('Ymd', strtotime($time_end));;
                if (0&&$time_start_db != $time_end_db) {
                    return json_encode([
                        'status' => 2,
                        'message' => '暂不支持跨天查询'
                    ]);
                }

                if ($out_trade_no) {
                    $where[] = ['out_trade_no', '=', $out_trade_no];
                } else {
                    if ($time_start) {
                        $where[] = ['created_at', '>=', $time_start];
                    }

                    if ($time_end) {
                        $where[] = ['created_at', '<=', $time_end];
                    }

                    if ($store_id) {
                        $where[] = ['store_id', '=', $store_id];
                    }
                }

                if ($user_id) {
                    $users = $this->getSubIds($user_id);
                } else {
                    $user_id = $public->user_id;
                    $users = $this->getSubIds($public->user_id);
                }

                if (!in_array($user_id, $users)) {
                    return json_encode(['status' => 2, 'message' => '非上下级关系']);
                }

                $User = User::where('id', $user_id)
                    ->select('money', 'settlement_money', 'unsettlement_money')
                    ->first();
                $money = $User->money;

                $table = 'user_wallet_details' . '_' . date('Ymd', strtotime($time_start));
                if (env('DB_D1_HOST')) {
                    if (Schema::hasTable($table)) {
                        $UserWalletDetail = DB::connection("mysql_d1")->table($table);
                    } else {
                        $UserWalletDetail = DB::connection("mysql_d1")->table("user_wallet_details");
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $UserWalletDetail = DB::table($table);
                    } else {
                        $UserWalletDetail = DB::table('user_wallet_details');
                    }
                }

                //获取下级所有返佣
                if ($request->get('user_id')) {
                    $detail = $UserWalletDetail->where($where)->where('user_id', $request->get('user_id'));
                } else {
                    $user_id = $public->user_id;
                    $detail = $UserWalletDetail->where($where)->where('user_id', $this->getSubIds($public->user_id));
                }

                if (env('DB_D1_HOST')) {
                    if (Schema::hasTable($table)) {
                        $UserWalletDetail2 = DB::connection("mysql_d1")->table($table);
                    } else {
                        $UserWalletDetail2 = DB::connection("mysql_d1")->table("user_wallet_details");
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $UserWalletDetail2 = DB::table($table);
                    } else {
                        $UserWalletDetail2 = DB::table('user_wallet_details');
                    }
                }

                if (env('DB_D1_HOST')) {
                    if (Schema::hasTable($table)) {
                        $UserWalletDetail3 = DB::connection("mysql_d1")->table($table);
                    } else {
                        $UserWalletDetail3 = DB::connection("mysql_d1")->table("user_wallet_details");
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $UserWalletDetail3 = DB::table($table);
                    } else {
                        $UserWalletDetail3 = DB::table('user_wallet_details');
                    }
                }

                $where[] = ['user_id', '=', $user_id];
                $settlement_money_where = $where;
                $settlement_money_where[] = ['settlement', '=', '01'];
                $unsettlement_money_where = $where;
                $unsettlement_money_where[] = ['settlement', '=', '02'];
                $settlement_money = $UserWalletDetail2->where($settlement_money_where)->select('money')->sum('money');
                $unsettlement_money = $UserWalletDetail3->where($unsettlement_money_where)->select('money')->sum('money');
            }

            $this->t = $detail->count();
            $detail = $this->page($detail)->orderBy('updated_at', 'desc')->get();
            $this->status = 1;
            $this->message = '数据返回成功';

            if ($return_type == '02') {
                $data = $detail;
            } elseif ($return_type == '03') {
                $data = $detail;
                $this->order_data = [
                    'all_money' => $settlement_money + $unsettlement_money,
                    'settlement_money' => '' . number_format($settlement_money, 4, '.', '') . '',
                    'unsettlement_money' => '' . number_format($unsettlement_money, 4, '.', '') . '',
                ];
            } else {
                $data = [
                    'money' => '' . number_format($money, 4, '.', '') . '',
                    'settlement_money' => '' . number_format($settlement_money, 4, '.', '') . '',
                    'unsettlement_money' => '' . number_format($unsettlement_money, 4, '.', '') . '',
                    'detail' => $detail,
                ];
            }

            return $this->format($data);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }
    
    //服务费充值记录，总和记录
    public function serivce_money(Request $request){
        $public = $this->parseToken();
        $store_id = $request->get('store_id', '');
        $user_id = $request->get('user_id', '');
        if(!empty($store_id)){
            $store=Store::where('store_id', $store_id)->first()->toarray();
            //扣费总额
            $obj = DB::table('service_day_money');
            $where[] = ['store_id', $store_id];
            $count = $obj->where($where)->select(DB::raw('sum(count) as count'))->get();
            $count=json_decode($count,true);
            $count=$count[0]['count'];

            //充值总额
            $obj1 = DB::table('fullmoney_log');
            $where[] = ['store_id', $store_id];
            $where[] = ['status', 2];
            $count1 = $obj1->where($where)->select(DB::raw('sum(total_price) as total_price'))->get();
            $count1=json_decode($count1,true);
            $count1=$count1[0]['total_price'];

            //充值记录
            $detail=DB::table('fullmoney_log')->where(array('store_id'=>$store_id,'status'=>2))->orderBy('created_at', 'desc')->get();
            $detail=json_decode($detail,true);
            foreach($detail as $k=>$v){
                $detail[$k]['created_at']=date("Y-m-d H:i:s",$v['created_at']);
            }
            $data = [
                'store_money' => $store['store_money'],
                'serivce_money' => empty($count)?0:$count,
                'charging_money' => empty($count1)?0:$count1,
                'detail' => $detail,
            ];
        }
        if(!empty($user_id)){
            $user=DB::table('users')->where('id',$user_id)->first();
            //扣费总额
            $obj = DB::table('service_day_money');
            $where[] = ['user_id', $user_id];
            $count = $obj->where($where)->select(DB::raw('sum(count) as count'))->get();
            $count=json_decode($count,true);
            $count=$count[0]['count'];

            //充值总额
            $obj1 = DB::table('fullmoney_log');
            $where[] = ['user_id', $user_id];
            $where[] = ['status', 2];
            $count1 = $obj1->where($where)->select(DB::raw('sum(total_price) as total_price'))->get();
            $count1=json_decode($count1,true);
            $count1=$count1[0]['total_price'];

            //充值记录
            $detail=DB::table('fullmoney_log')->where(array('user_id'=>$user_id,'status'=>2))->orderBy('created_at', 'desc')->get();
            $detail=json_decode($detail,true);
            foreach($detail as $k=>$v){
                $detail[$k]['created_at']=date("Y-m-d H:i:s",$v['created_at']);
            }
            $data = [
                'store_money' => $user->settlement_money,
                'serivce_money' => empty($count)?0:$count,
                'charging_money' => empty($count1)?0:$count1,
                'detail' => $detail,
            ];
        }
        return $this->format($data);
    }

    //单个返佣信息查询
    public function source_query_info(Request $request)
    {
        try {
            $public = $this->parseToken();
            $source_query_id = $request->get('source_query_id');
            if ($public->type == "user") {

                if (env('DB_D1_HOST')) {
                    $UserWalletDetail = DB::connection("mysql_d1")->table("user_wallet_details");
                } else {
                    $UserWalletDetail = DB::table('user_wallet_details');
                }

                $data = $UserWalletDetail->where('id', $source_query_id)->first();

            } else {
                if (env('DB_D1_HOST')) {
                    $merchant_wallet_details = DB::connection("mysql_d1")->table("merchant_wallet_details");
                } else {
                    $merchant_wallet_details = DB::table('merchant_wallet_details');
                }

                $data = $merchant_wallet_details->where('id', $source_query_id)->first();

            }
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);
        } catch (\Exception $exception) {

            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }


    //查询支付宝账户
    public function account(Request $request)
    {
        try {
            $public = $this->parseToken();
            if ($public->type == "merchant") {
                $user_id = $public->merchant_id;
                $account = MerchantAccount::where('merchant_id', $user_id)->first();
            }

            if ($public->type == "user") {
                $user_id = $public->user_id;
                $account = UserAccount::where('user_id', $user_id)->first();
            }

            if ($account) {
                $alipay_account = $account->alipay_account;
                $alipay_name = $account->alipay_name;
                $data = [
                    'alipay_account' => $alipay_account,
                    'alipay_name' => $alipay_name,
                ];
                $this->status = 1;
                $this->message = '数据返回成功';
                return $this->format($data);

            } else {
                return json_encode([
                    'status' => 2,
                    'message' => '未绑定支付宝账户'
                ]);
            }

        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }

    }


    //添加修改支付宝账户
    public function add_account(Request $request)
    {
        try {
            $public = $this->parseToken();
            $alipay_account = $request->get('alipay_account', '');
            $alipay_name = $request->get('alipay_name', '');
            $code = $request->get('code', '');


            //校验短信验证码
            if ($code != "" && $alipay_account == "" && $alipay_name == "") {
                //验证手机验证码
                $msn_local = Cache::get($public->phone . 'account');
                if ((string)$code != (string)$msn_local) {
                    return json_encode([
                        'status' => 2,
                        'message' => '短信验证码不匹配'
                    ]);
                } else {
                    return json_encode([
                        'status' => 1,
                        'message' => '短信验证码匹配成功',
                    ]);
                }
            }


            if ($public->type == "merchant") {
                $user_id = $public->merchant_id;
                $account = MerchantAccount::where('merchant_id', $user_id)->first();
            }

            if ($public->type == "user") {
                $user_id = $public->user_id;
                $account = UserAccount::where('user_id', $user_id)->first();

            }
            //修改
            if ($account) {
                $check_data = [
                    'alipay_account' => '支付宝账户',
                    'alipay_name' => '支付宝名称',
                    'code' => '短信验证码',
                ];
                $check = $this->check_required($request->except(['token']), $check_data);
                if ($check) {
                    return json_encode([
                        'status' => 2,
                        'message' => $check
                    ]);
                }

                $msn_local = Cache::get($public->phone . 'account');
                if ((string)$code != (string)$msn_local) {
                    return json_encode([
                        'status' => 2,
                        'message' => '短信验证码不匹配'
                    ]);
                }


                $account->alipay_account = $alipay_account;
                $account->alipay_name = $alipay_name;
                $account->save();


            } //添加
            else {

                $check_data = [
                    'alipay_account' => '支付宝账户',
                    'alipay_name' => '支付宝名称',
                ];

                $check = $this->check_required($request->except(['token']), $check_data);
                if ($check) {
                    return json_encode([
                        'status' => 2,
                        'message' => $check
                    ]);
                }


                if ($public->type == "merchant") {
                    $user_id = $public->merchant_id;
                    MerchantAccount::create([
                        'merchant_id' => $user_id,
                        'alipay_account' => $alipay_account,
                        'alipay_name' => $alipay_name,
                    ]);
                }

                if ($public->type == "user") {
                    $user_id = $public->user_id;
                    UserAccount::create([
                        'user_id' => $user_id,
                        'alipay_account' => $alipay_account,
                        'alipay_name' => $alipay_name,
                    ]);

                }

            }

            return json_encode([
                'status' => 1,
                'message' => '处理成功',
                'data' => $request->except(['token'])
            ]);


        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }

    }


    //提交提现操作
    public function out_wallet(Request $request)
    {

        try {

            $public = $this->parseToken();
            $config_id = $public->config_id;
            $total_amount = $request->get('total_amount');
            $alipay_account = $request->get('alipay_account');
            if ($public->type == "merchant") {
                $user_id = $public->merchant_id;
                $money = Merchant::where('id', $user_id)->first()->money;//钱包的钱
                $accounts = MerchantAccount::where('merchant_id', $user_id)->first();
                $SettlementConfig = SettlementConfig::where('dx', '2')->first();
            }

            if ($public->type == "user") {
                $user_id = $public->user_id;
                $money = User::where('id', $user_id)->first()->money;//钱包的钱
                $accounts = UserAccount::where('user_id', $user_id)->first();
                $SettlementConfig = SettlementConfig::where('dx', '1')->first();
            }

            if (!$accounts) {
                return json_encode(['status' => 2, 'message' => '提现账户未设置']);
            }


            if (!$SettlementConfig) {
                return json_encode(['status' => 2, 'message' => '服务商提现未设置']);
            }


            $sxf_amount = $SettlementConfig->sxf_amount;
            $tx_remark = $SettlementConfig->tx_remark;

            if ($total_amount < $sxf_amount) {
                return json_encode(['status' => 2, 'message' => '提现金额小于手续费' . $sxf_amount]);
            }

            if ($total_amount < $SettlementConfig->s_amount) {
                return json_encode(['status' => 2, 'message' => '提现金额不能小于' . $SettlementConfig->s_amount . '元']);
            }


            if ($total_amount > $SettlementConfig->e_amount) {
                return json_encode(['status' => 2, 'message' => '提现金额不能大于' . $SettlementConfig->e_amount . '元']);
            }


            $is_number = is_numeric($total_amount);
            if (!$is_number) {
                return json_encode(['status' => 2, 'message' => '提现金额类型不正确']);
            }


            $total_amount = number_format($total_amount, 2, '.', '');
            $time = date('Y-m-d h:i:s', time());
            $out_trade_no = date('Ymdhis', time());
            $money = number_format($money, 2, '.', '');
            $s = (bccomp($total_amount, $money, 2));//比较浮点型大小

            if ($s == 1) {
                return json_encode(['status' => 2, 'message' => '你的钱包余额里只有' . $money . '元没有办法提现' . $total_amount]);
            }
            if ($accounts && $accounts->alipay_account) {
                //提交过来的支付宝必须是绑定的支付宝
                if ($alipay_account != $accounts->alipay_account) {
                    return json_encode(['status' => 2, 'message' => '提现支付宝和绑定的支付宝不一致']);
                }
                //开启事务
                try {
                    DB::beginTransaction();
                    if ($public->type == "merchant") {
                        $user_id = $public->merchant_id;
                        $updateMonery = $money - $total_amount;
                        $data = [
                            'merchant_id' => $user_id,
                            'out_trade_no' => $out_trade_no,
                            'trade_no' => '',
                            'account' => $accounts->alipay_account,
                            'name' => $accounts->alipay_name,
                            'amount' => $total_amount,
                            'account_amount' => $updateMonery,
                            'status' => 2,
                            'status_desc' => '提现申请中',
                            'config_id' => $config_id,
                            'sxf_amount' => $sxf_amount,
                            'remark' => ''
                        ];
                        MerchantWithdrawalsRecords::create($data);
                        Merchant::where('id', $user_id)->update(['money' => $updateMonery]);

                    }

                    if ($public->type == "user") {
                        $user_id = $public->user_id;
                        $updateMonery = $money - $total_amount;
                        $data = [
                            'user_id' => $user_id,
                            'out_trade_no' => $out_trade_no,
                            'trade_no' => $out_trade_no,
                            'account' => $accounts->alipay_account,
                            'name' => $accounts->alipay_name,
                            'amount' => $total_amount,
                            'account_amount' => $updateMonery,
                            'status' => 2,
                            'status_desc' => '提现申请中',
                            'config_id' => $config_id,
                            'sxf_amount' => $sxf_amount,
                            'remark' => ''
                        ];
                        UserWithdrawalsRecords::create($data);
                        User::where('id', $user_id)->update(['money' => $updateMonery]);

                    }
                    DB::commit();
                } catch (\Exception $e) {
                    Log::info($e);
                    DB::rollBack();
                    return json_encode(['status' => 2, 'message' => $e->getMessage()]);
                }


                $AlipayTransfer = new \App\Common\AlipayTransfer($out_trade_no, $public->type, $total_amount, $alipay_account, $accounts->alipay_name, $config_id, $sxf_amount, $tx_remark);
                $AlipayTransfer->insert();


            } else {
                return json_encode(['status' => 2, 'message' => '没有绑定收银员账号']);
            }


            return json_encode(['status' => 1, 'message' => '提现申请成功', 'data' => $request->except(['token'])]);


        } catch (\Exception $exception) {
            Log::info($exception);
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }


    }


    //提现记录
    public function out_wallet_list(Request $request)
    {

        try {
            $public = $this->parseToken();
            $time_start = $request->get('time_start', '');
            $time_end = $request->get('time_end', '');
            $user_id = $request->get('user_id', '');
            $where = [];
            if ($time_start) {
                $where[] = ['updated_at', '>=', $time_start];
            }
            if ($time_end) {
                $where[] = ['updated_at', '<=', $time_end];
            }

            if ($public->type == "merchant") {
                $user_id = $public->merchant_id;

                $where[] = ['merchant_id', '=', $user_id];


                if (env('DB_D1_HOST')) {
                    $MerchantWithdrawalsRecords = DB::connection("mysql_d1")->table("merchant_withdrawals_records");
                } else {
                    $MerchantWithdrawalsRecords = DB::table('merchant_withdrawals_records');
                }

                $data = $MerchantWithdrawalsRecords->where($where);
            }

            if ($public->type == "user") {

                if ($user_id) {
                    $users = $this->getSubIds($user_id);
                } else {
                    $user_id = $public->user_id;
                    $users = $this->getSubIds($public->user_id);

                }
                if (!in_array($user_id, $users)) {
                    return json_encode(['status' => 2, 'message' => '非上下级关系']);
                }


                if (env('DB_D1_HOST')) {
                    $UserWithdrawalsRecords = DB::connection("mysql_d1")->table("user_withdrawals_records");
                } else {
                    $UserWithdrawalsRecords = DB::table('user_withdrawals_records');
                }
                //获取下级所有返佣
                if ($request->get('user_id')) {
                    $where[] = ['user_id', '=', $request->get('user_id')];
                    $data = $UserWithdrawalsRecords->where($where);
                } else {
                    $data = $UserWithdrawalsRecords->where($where)
                        ->whereIn('user_id', $this->getSubIds($public->user_id));
                }

            }
            $this->message = '数据返回成功';
            $this->t = $data->count();
            $data = $this->page($data)->orderBy('updated_at', 'desc')->get();
            return $this->format($data);

        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }

    }

    //单个提现记录信息查询
    public function records_query_info(Request $request)
    {
        try {
            $public = $this->parseToken();
            $records_query_id = $request->get('records_query_id');
            if ($public->type == "user") {
                if (env('DB_D1_HOST')) {
                    $UserWithdrawalsRecords = DB::connection("mysql_d1")->table("user_withdrawals_records");
                } else {
                    $UserWithdrawalsRecords = DB::table('user_withdrawals_records');
                }
                $data = $UserWithdrawalsRecords->where('id', $records_query_id)->first();
            } else {
                if (env('DB_D1_HOST')) {
                    $MerchantWithdrawalsRecords = DB::connection("mysql_d1")->table("merchant_withdrawals_records");
                } else {
                    $MerchantWithdrawalsRecords = DB::table('merchant_withdrawals_records');
                }
                $data = $MerchantWithdrawalsRecords->where('id', $records_query_id)->first();
            }
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);
        } catch (\Exception $exception) {

            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }


    //结算 目前只支持 代理结算
    public function settlement(Request $request)
    {
        try {
            $public = $this->parseToken();
            $user_id = $request->get('user_id', '');
            $user_name = $request->get('user_name', '');
            $store_name = $request->get('store_name', '');
            $store_id = $request->get('store_id', '');
            $time_start = $request->get('time_start');
            $time_end = $request->get('time_end');
            $pay_password = $request->get('pay_password');
            $source_type = $request->get('source_type');
            $source_type_desc = $request->get('source_type_desc');
            $dx = $request->get('dx', '');
            $rate = $request->get('rate', '');

            $config_id = $public->config_id;
            $s_no = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999)) . $config_id . $user_id . $source_type;
            $day = date('Ymd', strtotime($time_start));


            $check_data = [
                'time_start' => '开始时间',
                'time_end' => '结束时间',
                'pay_password' => '支付密码',
                'source_type' => '返佣来源',
                'source_type_desc' => '返佣来源说明',
                'dx' => '对象',
                'rate' => '税点'

            ];


            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }


            if (env('DB_D1_HOST')) {
                $settlement_lists = DB::connection("mysql_d1")->table("settlement_lists");
            } else {
                $settlement_lists = DB::table('settlement_lists');
            }

            //如果有未结算的记录 不允许结算
            $SettlementList = $settlement_lists->where('is_true', 0)
                ->where('config_id', $config_id)
                ->select('id')
                ->first();

            if ($SettlementList) {
                return json_encode([
                    'status' => 2,
                    'message' => '请先处理未结算订单'
                ]);
            }


            $user = User::where('id', $public->user_id)->first();
            $hasPermission = $user->hasPermissionTo('结算');
            if (!$hasPermission) {
                return json_encode(['status' => 2, 'message' => '没有权限结算']);
            }

            if ($public->pid) {
                return json_encode(['status' => 2, 'message' => '没有权限结算']);
            }


            //服务商
            if ($dx == "1") {
                $dx_desc = "服务商";
                if ($user_name && $user_name != "NULL") {
                    $dx_desc = $user_name;
                }

                //不允许跨天操作
                $time_start_db = date('Ymd', strtotime($time_start));
                $time_end_db = date('Ymd', strtotime($time_end));;
                if (0&&$time_start_db != $time_end_db) {
                    return json_encode([
                        'status' => 2,
                        'message' => '暂不支持跨天查询'
                    ]);
                }

                //查出时间段的返佣未结算用户列表
                $where = [];
                $where[] = ['settlement', '02'];
                $where[] = ['money', '!=', '0.0000'];

                if ($source_type) {
                    $where[] = ['source_type', $source_type];
                }
                if ($time_start) {
                    $where[] = ['created_at', '>=', $time_start];
                }
                if ($time_end) {
                    $where[] = ['created_at', '<=', $time_end];
                }


                $table = 'user_wallet_details' . '_' . $day;
                if (env('DB_D1_HOST')) {
                    if (Schema::hasTable($table)) {
                        $UserWalletDetail = DB::connection("mysql_d1")->table($table);
                    } else {
                        $UserWalletDetail = DB::connection("mysql_d1")->table("user_wallet_details");
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $UserWalletDetail = DB::table($table);
                    } else {
                        $UserWalletDetail = DB::table('user_wallet_details');
                    }
                }

                //选择某个服务商
                if ($user_id && $user_id != "NULL") {
                    $user_ids = $this->getSubIds($user_id);
                    $users_obj = $UserWalletDetail->where($where)
                        ->whereIn('user_id', $user_ids)
                        ->select('user_id')
                        ->distinct('user_id')//去重
                        ->get();

                } else {
                    $users_obj = $UserWalletDetail->where($where)
                        ->select('user_id')
                        ->distinct('user_id')//去重
                        ->get();
                }


                if ($users_obj->isEmpty()) {
                    return json_encode([
                        'status' => 2,
                        'message' => '没有找到结算记录'
                    ]);
                }

                //开启事务
                try {
                    DB::beginTransaction();

                    $total_amount = 0;
                    $total_get_amount = 0;
                    //整个大的平台
                    $insert1 = [
                        'config_id' => $config_id,
                        's_no' => $s_no,
                        'dx' => $dx,
                        'dx_desc' => $dx_desc,
                        's_time' => $time_start,
                        'e_time' => $time_end,
                        'source_type' => $source_type,
                        'source_type_desc' => $source_type_desc,
                        'total_amount' => $total_amount,
                        'get_amount' => $total_get_amount,
                        'rate' => $rate,
                        'is_true' => 0,
                        'dx_id' => isset($user_id) ? $user_id : "",
                    ];
                    $SettlementList = SettlementList::create($insert1);
                    $settlement_list_id = $SettlementList->id;

                    foreach ($users_obj as $k => $v) {
                        $user_id = $v->user_id;

                        $table = 'user_wallet_details' . '_' . $day;
                        if (env('DB_D1_HOST')) {
                            if (Schema::hasTable($table)) {
                                $UserWalletDetail1 = DB::connection("mysql_d1")->table($table);
                            } else {
                                $UserWalletDetail1 = DB::connection("mysql_d1")->table("user_wallet_details");
                            }
                        } else {
                            if (Schema::hasTable($table)) {
                                $UserWalletDetail1 = DB::table($table);
                            } else {
                                $UserWalletDetail1 = DB::table('user_wallet_details');
                            }
                        }

                        $UserWalletDetail1 = $UserWalletDetail1->where('source_type', $source_type)
                            ->where('created_at', '>', $time_start)
                            ->where('created_at', '<', $time_end)
                            ->where('settlement', '02')
                            ->where('user_id', $v->user_id)
                            ->select('money');


                        $money = $UserWalletDetail1->sum('money');
                        //总金额
                        $total_amount = $total_amount + $money;
                        $j = number_format($rate / 100, 4, '.', '');
                        $get_amount = $money - (($money * $j));
                        $get_amount = number_format($get_amount, 4, '.', '');
                        $total_get_amount = $total_get_amount + $get_amount;

                        //个人金额
                        $insert = [
                            's_no' => $s_no,
                            'config_id' => $config_id,
                            'dx' => $dx,
                            's_time' => $time_start,
                            'e_time' => $time_end,
                            'source_type' => $source_type,
                            'source_type_desc' => $source_type_desc,
                            'total_amount' => $money,
                            'get_amount' => $get_amount,
                            'user_id' => $user_id,
                            'is_true' => 0,
                            'rate' => $rate,
                            'settlement_list_id' => $settlement_list_id
                        ];
                        SettlementListInfo::create($insert);
                    }

                    SettlementList::where('id', $settlement_list_id)->update([
                        'get_amount' => $total_get_amount,
                        'total_amount' => $total_amount,
                        's_time' => $time_start,
                        'e_time' => $time_end,
                    ]);


                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    return json_encode(['status' => 2, 'message' => $e->getMessage()]);
                }


            } else {

                $store = Store::where('store_id', $store_id)
                    ->select('merchant_id')
                    ->first();

                if (!$store) {
                    return json_encode([
                        'status' => 2,
                        'message' => '请选择门店'
                    ]);
                }
                $user_id = $store->merchant_id;
                $dx_desc = "全部活动商户";
                if ($store_name && $store_name != "NULL") {
                    $dx_desc = $store_name;
                }
                //查出时间段的返佣未结算用户列表
                $where = [];
                $where[] = ['settlement', '02'];
                $where[] = ['money', '!=', '0.0000'];

                if ($source_type) {
                    $where[] = ['source_type', $source_type];
                }
                if ($store_id) {
                    $where[] = ['store_id', '=', $store_id];
                }
                $time_start_YMD = date('Y-m-d', strtotime($time_start));
                $time_end_YMD = date('Y-m-d', strtotime($time_end));


                if (env('DB_D1_HOST')) {
                    $merchant_wallet_day_counts = DB::connection("mysql_d1")->table("merchant_wallet_day_counts");
                } else {
                    $merchant_wallet_day_counts = DB::table('merchant_wallet_day_counts');
                }

                $MerchantWalletDayCount = $merchant_wallet_day_counts->whereBetween('day', [$time_start_YMD, $time_end_YMD])
                    ->where($where)
                    ->select('id')
                    ->first();


                if (!$MerchantWalletDayCount) {
                    return json_encode([
                        'status' => 2,
                        'message' => '没有找到结算记录'
                    ]);
                }

                //开启事务
                try {
                    DB::beginTransaction();

                    $total_amount = 0;
                    $total_get_amount = 0;
                    //整个大的平台
                    $insert1 = [
                        'config_id' => $config_id,
                        's_no' => $s_no,
                        'dx' => $dx,
                        'dx_id' => $user_id,
                        'dx_desc' => $dx_desc,
                        's_time' => $time_start,
                        'e_time' => $time_end,
                        'source_type' => $source_type,
                        'source_type_desc' => $source_type_desc,
                        'total_amount' => $total_amount,
                        'get_amount' => $total_get_amount,
                        'rate' => $rate,
                        'is_true' => 0,
                        'is_settlement' => 0,
                    ];
                    $SettlementList = SettlementList::create($insert1);
                    $settlement_list_id = $SettlementList->id;


                    $table = 'merchant_wallet_details' . '_' . date('Ymd', strtotime($time_start));
                    if (env('DB_D1_HOST')) {
                        if (Schema::hasTable($table)) {
                            $merchant_wallet_details = DB::connection("mysql_d1")->table($table);
                        } else {
                            $merchant_wallet_details = DB::connection("mysql_d1")->table("merchant_wallet_details");
                        }
                    } else {
                        if (Schema::hasTable($table)) {
                            $merchant_wallet_details = DB::table($table);
                        } else {
                            $merchant_wallet_details = DB::table('merchant_wallet_details');
                        }
                    }

                    $MerchantWalletDetail = $merchant_wallet_details->where('source_type', $source_type)
                        ->where('created_at', '>', $time_start)
                        ->where('created_at', '<', $time_end)
                        ->where('settlement', '02')
                        ->where('store_id', $store_id)
                        ->select('money');

                    $money = $MerchantWalletDetail->sum('money');
                    //总金额
                    $total_amount = $total_amount + $money;
                    $j = number_format($rate / 100, 4, '.', '');
                    $get_amount = $money - (($money * $j));
                    $get_amount = number_format($get_amount, 4, '.', '');
                    $total_get_amount = $total_get_amount + $get_amount;


                    //每个门店的金额
                    $insert = [
                        's_no' => $s_no,
                        'config_id' => $config_id,
                        'dx' => $dx,
                        's_time' => $time_start,
                        'e_time' => $time_end,
                        'source_type' => $source_type,
                        'source_type_desc' => $source_type_desc,
                        'total_amount' => $money,
                        'get_amount' => $get_amount,
                        'user_id' => $user_id,//收银员ID
                        'is_true' => 0,
                        'rate' => $rate,
                        'settlement_list_id' => $settlement_list_id
                    ];
                    SettlementListInfo::create($insert);


                    SettlementList::where('id', $settlement_list_id)->update([
                        'get_amount' => $total_get_amount,
                        'total_amount' => $total_amount,
                    ]);


                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    return json_encode(['status' => 2, 'message' => $e->getMessage()]);
                }

            }

            return json_encode(['status' => 1, 'message' => '结算请求处理添加成功']);

        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }

    }


    //结算列表
    public function settlement_lists(Request $request)
    {
        try {
            $public = $this->parseToken();
            $config_id = $public->config_id;
            $dx = $request->get('dx', '');
            $source_type = $request->get('source_type', '');


            $where = [];
            if ($dx) {
                $where[] = ['dx', $dx];
            }
            if ($config_id) {
                $where[] = ['config_id', $config_id];
            }
            if ($source_type) {
                $where[] = ['source_type', $source_type];
            }


            if (env('DB_D1_HOST')) {
                $settlement_lists = DB::connection("mysql_d1")->table("settlement_lists");
            } else {
                $settlement_lists = DB::table('settlement_lists');
            }
            $obj = $settlement_lists->where($where);
            $this->t = $obj->count();
            $data = $this->page($obj)->orderBy('updated_at', 'desc')->get();
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);

        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }

    //结算明细
    public function settlement_list_infos(Request $request)
    {
        try {
            $public = $this->parseToken();
            $dx = $request->get('dx', '');
            $settlement_list_id = $request->get('settlement_list_id', '');
            $user_name = $request->get('user_name', '');
            $user_id = $request->get('user_id', '');


            if (env('DB_D1_HOST')) {
                $settlement_lists = DB::connection("mysql_d1")->table("settlement_lists");
            } else {
                $settlement_lists = DB::table('settlement_lists');
            }

            $SettlementList = $settlement_lists->where('id', $settlement_list_id)
                ->select('dx')
                ->first();

            if (!$SettlementList) {
                return json_encode(['status' => 2, 'message' => '没有找到记录']);

            }

            $dx = $SettlementList->dx;//对象类型 1 代理商 2服务商

            $where = [];
            $config_id = $public->config_id;

            if ($settlement_list_id) {
                $where[] = ['settlement_list_infos.settlement_list_id', $settlement_list_id];
            }
            if ($user_id) {
                $where[] = ['settlement_list_infos.user_id', $user_id];
            }

            if ($settlement_list_id) {
                $where[] = ['settlement_list_infos.settlement_list_id', $settlement_list_id];
            }

            if ($dx) {
                $where[] = ['settlement_list_infos.dx', $dx];
            }
            if ($config_id) {
                $where[] = ['settlement_list_infos.config_id', $config_id];
            }


            if (env('DB_D1_HOST')) {
                $settlement_list_infos = DB::connection("mysql_d1")->table("settlement_list_infos");
            } else {
                $settlement_list_infos = DB::table('settlement_list_infos');
            }

            if ($user_name) {
                if (is_numeric($user_name)) {
                    if ($dx == 1) {
                        $obj = $settlement_list_infos->where($where)
                            ->join('users', 'settlement_list_infos.user_id', '=', 'users.id')
                            ->where('users.phone', $user_name);
                    } else {
                        $obj = $settlement_list_infos->where($where)
                            ->join('merchants', 'settlement_list_infos.user_id', '=', 'merchants.id')
                            ->where('merchants.phone', $user_name);
                    }

                } else {
                    if ($dx == 1) {
                        $obj = $settlement_list_infos->where($where)
                            ->join('users', 'settlement_list_infos.user_id', '=', 'users.id')
                            ->where('merchants.name', $user_name);
                    } else {
                        $obj = $settlement_list_infos->where($where)
                            ->join('merchants', 'settlement_list_infos.user_id', '=', 'merchants.id')
                            ->where('merchants.name', $user_name);
                    }

                }

            } else {
                if ($dx == 1) {
                    $obj = $settlement_list_infos->join('users', 'settlement_list_infos.user_id', '=', 'users.id')
                        ->where($where);
                } else {
                    $obj = $settlement_list_infos->join('merchants', 'settlement_list_infos.user_id', '=', 'merchants.id')
                        ->where($where);
                }


            }

            $this->t = $obj->count();

            if ($dx == 1) {
                $data = $this->page($obj)->select('settlement_list_infos.*', 'users.name as user_name', 'users.phone')
                    ->get();
            } else {
                $data = $this->page($obj)->select('settlement_list_infos.*', 'merchants.name as user_name', 'merchants.phone')
                    ->get();
            }


            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);

        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }


    //删除结算列表明细
    public function settlement_list_del(Request $request)
    {
        try {
            $public = $this->parseToken();
            $config_id = $public->config_id;
            $settlement_list_id = $request->get('settlement_list_id', '');
            $where = [];


            $s = SettlementList::where('id', $settlement_list_id)
                ->where('config_id', $config_id)
                ->first();
            if (!$s) {
                return json_encode([
                    'status' => 2,
                    'message' => '结算ID不存在'
                ]);
            }

            if ($s->is_true) {
                return json_encode([
                    'status' => 2,
                    'message' => '已经确认的结算无法删除'
                ]);
            }

            //开启事务
            try {
                DB::beginTransaction();

                //删除列表
                $s->delete();

                //删除明细
                SettlementListInfo::where('settlement_list_id', $settlement_list_id)
                    ->where('config_id', $config_id)
                    ->delete();

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return json_encode(['status' => 2, 'message' => $e->getMessage()]);
            }

            $this->status = 1;
            $this->message = '删除成功';
            return $this->format([]);

        } catch (\Exception $exception) {
            return json_encode(
                [
                    'status' => -1,
                    'message' => $exception->getMessage()
                ]
            );
        }
    }


    //确认结算
    public function settlement_list_true(Request $request)
    {
        try {
            $public = $this->parseToken();
            $config_id = $public->config_id;
            $settlement_list_id = $request->get('settlement_list_id', '');


            $user = User::where('id', $public->user_id)->first();
            $hasPermission = $user->hasPermissionTo('确认结算');
            if (!$hasPermission) {
                return json_encode(['status' => 2, 'message' => '没有权限确认']);
            }

            if ($public->pid) {
                return json_encode(['status' => 2, 'message' => '没有权限确认']);
            }

            $where = [];
            $list_info_id = $request->get('list_info_id', '');

            if ($list_info_id) {

                if (env('DB_D1_HOST')) {
                    $settlement_list_infos = DB::connection("mysql_d1")->table("settlement_list_infos");
                } else {
                    $settlement_list_infos = DB::table('settlement_list_infos');
                }

                $SettlementListInfo = $settlement_list_infos->where('id', $list_info_id)
                    ->where('config_id', $config_id)
                    ->first();


                if ($SettlementListInfo) {
                    $SettlementListInfo->is_true = 1;
                    $SettlementListInfo->save();
                }
                return json_encode([
                    'status' => 1,
                    'message' => '确认成功'
                ]);

            }


            if ($settlement_list_id) {
                $s = SettlementList::where('id', $settlement_list_id)
                    ->where('config_id', $config_id)
                    ->first();

                if (!$s) {
                    return json_encode([
                        'status' => 2,
                        'message' => 'settlement_list_id不存在'
                    ]);
                }


            } else {
                return json_encode([
                    'status' => 2,
                    'message' => 'settlement_list_id不存在'
                ]);
            }


            //开启事务
            try {
                DB::beginTransaction();

                //1.状态全部改成结算
                $s_time = $s->s_time;//开始时间
                $e_time = $s->e_time;//结束时间
                $source_type = $s->source_type;
                $s_no = $s->s_no;
                $dx = $s->dx;
                $dx_id = $s->dx_id;
                $day = date('Ymd', strtotime($s_time));

                //服务商
                if ($dx == 1) {
                    $UserWalletDetailwhere = [];
                    //如果针对代理商就是单独结算
                    if ($dx_id) {
                        $UserWalletDetailwhere[] = ['user_id', $dx_id];
                    }

                    $table = 'user_wallet_details' . '_' . $day;


                    if (Schema::hasTable($table)) {
                        $UserWalletDetail = DB::table($table);
                    } else {
                        $UserWalletDetail = DB::table('user_wallet_details');
                    }


                    $UserWalletDetail->where('source_type', $source_type)
                        ->where('created_at', '>=', $s_time)
                        ->where('created_at', '<=', $e_time)
                        ->where('settlement', '02')
                        ->where($UserWalletDetailwhere)
                        ->update([
                            'settlement' => '01',
                            'settlement_desc' => "已结算",
                        ]);


                    //2.将已经结算的金额入库
                    $SettlementListInfo = SettlementListInfo::where('settlement_list_id', $settlement_list_id)
                        ->where('s_no', $s_no)
                        ->select('get_amount', 'user_id')
                        ->get();

                    foreach ($SettlementListInfo as $k => $v) {
                        if ($v->get_amount == 0.0000) {
                            continue;
                        }

                        //金额相加
                        $user = User::where('id', $v->user_id)->first();

                        if (!$user) {
                            continue;
                        }
                        $user->money = $user->money + $v->get_amount;
                        $user->save();
                    }

                    $s->is_true = 1;
                    $s->save();

                } else {
                    //商户
                    //针对单个门店
                    $MerchantWalletDetailwhere = [];
                    if ($dx_id) {
                        $MerchantWalletDetailwhere[] = ['merchant_id', $dx_id];
                    }


                    $table = 'merchant_wallet_details' . '_' . $day;

                    if (Schema::hasTable($table)) {
                        $merchant_wallet_details = DB::table($table);
                    } else {
                        $merchant_wallet_details = DB::table('merchant_wallet_details');
                    }

                    $merchant_wallet_details->where('source_type', $source_type)
                        ->where($MerchantWalletDetailwhere)
                        ->where('created_at', '>=', $s_time)
                        ->where('created_at', '<=', $e_time)
                        ->where('settlement', '02')
                        ->update([
                            'settlement' => '01',
                            'settlement_desc' => "已结算",
                        ]);

                    //2.将已经结算的金额入库
                    $SettlementListInfo = SettlementListInfo::where('settlement_list_id', $settlement_list_id)
                        ->where('s_no', $s_no)
                        ->select('get_amount', 'user_id')
                        ->get();

                    foreach ($SettlementListInfo as $k => $v) {

                        if ($v->get_amount == 0.0000) {
                            continue;
                        }

                        //金额相加
                        $Merchant = Merchant::where('id', $v->user_id)->first();

                        if (!$Merchant) {
                            continue;
                        }
                        $Merchant->money = $Merchant->money + $v->get_amount;
                        $Merchant->save();
                    }

                    $s->is_true = 1;
                    $s->save();
                }

                DB::commit();
            } catch (\Exception $e) {
                Log::info($e);
                DB::rollBack();
                return json_encode(['status' => 2, 'message' => $e->getMessage()]);
            }

            $this->status = 1;
            $this->message = '结算成功';
            return $this->format([]);

        } catch (\Exception $exception) {
            return json_encode(['status' => -1,
                'message' => $exception->getMessage()]);
        }
    }

    //商户结算补录
    public function tf_settlemment(Request $request)
    {
        try {

            //传化
            $source_type = '12000';
            $source_type = $request->get('source_type', $source_type);
            $time = date("Y-m-d", time());
            $time = $request->get('time', $time);
            $settlement = $request->get('settlement', '02');

            $MerchantWalletDayCount = MerchantWalletDayCount::where('day', '<', $time)
                ->where('source_type', $source_type)
                ->where('settlement', $settlement)
                ->select('store_id', 'merchant_id', 'money', 'day', 'id')
                ->first();

            echo '通道类型:' . $source_type;
            echo '</br>';


            if ($MerchantWalletDayCount) {

                echo '门店ID:' . $MerchantWalletDayCount->store_id;
                echo '</br>';


                $merchant_id = $MerchantWalletDayCount->merchant_id;
                $money = $MerchantWalletDayCount->money;
                $day = $MerchantWalletDayCount->day;
                $s_time = date("Y-m-d 00:00:00", strtotime($day));
                $e_time = date("Y-m-d 23:59:59", strtotime($day));


                echo '结算时间段:' . $s_time . '-' . $e_time;
                echo '</br>';


                echo '结算金额:' . $money;
                echo '</br>';


                $id = $MerchantWalletDayCount->id;
                //开启事务
                try {
                    DB::beginTransaction();


                    //总表结算
                    MerchantWalletDayCount::where('id', $id)->update([
                        'settlement' => '01',
                    ]);


                    $table = 'merchant_wallet_details' . '_' . $day;

                    if (Schema::hasTable($table)) {
                        $merchant_wallet_details = DB::table($table);
                    } else {
                        $merchant_wallet_details = DB::table('merchant_wallet_details');
                    }


                    //明细结算
                    $merchant_wallet_details->where('source_type', $source_type)
                        ->where('merchant_id', $merchant_id)
                        ->where('created_at', '>=', $s_time)
                        ->where('created_at', '<=', $e_time)
                        ->where('settlement', '02')
                        ->update([
                            'settlement' => '01',
                            'settlement_desc' => "已结算",
                        ]);
                    //用户金额结算
                    $Merchant = Merchant::where('id', $merchant_id)
                        ->first();
                    if ($Merchant) {
                        echo '商户余额:' . $Merchant->money;
                        echo '</br>';
                        $all = $Merchant->money + $money;
                        echo '结算后商户余额:' . $all;
                        echo '</br>';

                        $Merchant->money = $Merchant->money + $money;
                        $Merchant->save();

                        echo '结算成功';
                        echo '</br>';
                    }


                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    dd($e);
                }
            } else {
                dd('暂无需要结算记录');
            }
        } catch (\Exception $exception) {
            dd($exception);
        }
    }


    //结算商户未结算的信息
    public function tf_settlemment_m(Request $request)
    {
        try {

            //传化
            $source_type = '12000';
            $source_type = $request->get('source_type', $source_type);
            $day = $request->get('day', '');
            $settlement = $request->get('settlement', '02');


            echo '通道类型:' . $source_type;
            echo '</br>';

            //开启事务
            try {
                DB::beginTransaction();


                $table = 'merchant_wallet_details' . '_' . $day;
                $merchant_wallet_details = DB::table($table);


                $merchant_obj_store = $merchant_wallet_details->where('source_type', $source_type)
                    ->where('settlement', $settlement)
                    ->select('store_id', 'merchant_id', 'money')
                    ->first();
                if (!$merchant_obj_store) {
                    dd('全部结算结束');
                }

                $table = 'merchant_wallet_details' . '_' . $day;
                $merchant_wallet_details = DB::table($table);

                //明细结算
                $money = $merchant_wallet_details->where('source_type', $source_type)
                    ->where('settlement', $settlement)
                    ->where('store_id', $merchant_obj_store->store_id)
                    ->select('money')
                    ->sum('money');


                $merchant_id = $merchant_obj_store->merchant_id;

                //用户金额结算
                $Merchant = Merchant::where('id', $merchant_id)->first();
                if ($Merchant) {
                    echo '门店ID:' . $merchant_obj_store->store_id;
                    echo '</br>';
                    echo '商户余额:' . $Merchant->money;
                    echo '</br>';
                    echo '补结算余额:' . $money;
                    echo '</br>';
                    $all = $Merchant->money + $money;
                    echo '结算后商户余额:' . $all;
                    echo '</br>';

                    $Merchant->money = $Merchant->money + $money;
                    $Merchant->save();

                    $table = 'merchant_wallet_details' . '_' . $day;
                    $merchant_wallet_details = DB::table($table);

                    $merchant_wallet_details->where('settlement', $settlement)
                        ->where('store_id', $merchant_obj_store->store_id)
                        ->update(['settlement' => '01', 'settlement_desc' => "已结算"]);
                    echo '结算成功';
                    echo '</br>';


                } else {
                    $table = 'merchant_wallet_details' . '_' . $day;
                    $merchant_wallet_details = DB::table($table);

                    $merchant_wallet_details->where('settlement', $settlement)
                        ->where('store_id', $merchant_obj_store->store_id)
                        ->update(['settlement' => '04', 'settlement_desc' => "找不到结算人"]);
                    echo '找不到结算人';
                    echo '</br>';
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                dd($e);
            }

        } catch (\Exception $exception) {
            dd($exception);
        }
    }

    //代理结算补录
    public function tf_user_settlemment(Request $request)
    {
        try {

            //传化
            $company = $request->get('company', 'tfpay');
            $is_settlement_user = $request->get('is_settlement_user', '02');
            $out_trade_no = $request->get('out_trade_no', '');


            if (env('DB_D1_HOST')) {
                $obj = DB::connection("mysql_d1")->table("orders");
            } else {
                $obj = DB::table('orders');
            }

            $where = [];
            if ($out_trade_no) {
                $where[] = ['out_trade_no', $out_trade_no];

                $order = $obj->where($where)
                    ->where('pay_status', 1)
                    ->select(
                        'id',
                        'out_trade_no',
                        'config_id',
                        'rate',
                        'store_id',
                        'user_id',
                        'ways_type',
                        'total_amount',
                        'created_at'
                    )
                    ->first();
            } else {
                $order = $obj->where('company', $company)
                    ->where('is_settlement_user', $is_settlement_user)
                    ->where('created_at', '>', '2019-11-11 00:00:00')
                    ->where('created_at', '<', date('Y-m-d 00:00:00', time()))
                    ->where('pay_status', 1)
                    ->select(
                        'id',
                        'out_trade_no',
                        'config_id',
                        'rate',
                        'store_id',
                        'user_id',
                        'ways_type',
                        'total_amount',
                        'created_at'
                    )
                    ->first();
            }


            if (!$order) {
                dd('全部补录制完毕');
            }
            $time_start = $order->created_at;
            $table = 'user_wallet_details' . '_' . date('Ymd', strtotime($time_start));
            if (env('DB_D1_HOST')) {
                if (Schema::hasTable($table)) {
                    $UserWalletDetail = DB::connection("mysql_d1")->table($table);
                } else {
                    $UserWalletDetail = DB::connection("mysql_d1")->table("user_wallet_details");
                }
            } else {
                if (Schema::hasTable($table)) {
                    $UserWalletDetail = DB::table($table);
                } else {
                    $UserWalletDetail = DB::table('user_wallet_details');
                }
            }
            $UserWalletDetail = $UserWalletDetail->where('out_trade_no', $order->out_trade_no)
                ->select('id')
                ->first();
            if ($UserWalletDetail) {
                Order::where('id', $order->id)->update(['is_settlement_user' => '01']);
                echo '订单号：' . $order->out_trade_no;
                echo '<br>';
                echo '无需补录';
            } else {
                $UserGetMoney = [
                    'config_id' => $order->config_id,//服务商ID
                    'user_id' => $order->user_id,//直属代理商
                    'store_id' => $order->store_id,//门店
                    'out_trade_no' => $order->out_trade_no,//订单号
                    'ways_type' => $order->ways_type,//通道类型
                    'order_total_amount' => $order->total_amount,//交易金额
                    'store_ways_type_rate' => $order->rate,//交易时的费率
                    'source_type' => '12000',//返佣来源
                    'source_desc' => 'TF-补',//返佣来源说明
                ];

                $obj = new  UserGetMoney($UserGetMoney);
                $obj->insert();
                echo '订单号：' . $order->out_trade_no;
                echo '<br>';
                echo '补录成功';
                Order::where('id', $order->id)->update(['is_settlement_user' => '01']);
            }


        } catch (\Exception $exception) {
            dd($exception);
        }
    }


    //总结算
    public function tf_settlemment_all(Request $request)
    {
        try {

            //传化
            $store_id = $request->get('store_id', '');
            $time_s = "2019-09-01 00:00:00";
            $time_e = "2019-11-28 23:59:59";

            $store = Store::where('store_id', $store_id)->select('id', 'pid')->first();
            if (!$store) {
                dd('门店不存在');
            }

            $store_ids = $this->getStore_id($store_id, $store->id);
            //分店
            if ($store->pid) {
                dd('请提供总店ID');
            }
            //开启事务
            try {
                DB::beginTransaction();


                //300以下交易额
                $total_amount = Order::whereIn('store_id', $store_ids)
                    ->where('pay_status', 1)
                    ->where('total_amount', '>', '2')
                    ->where('company', 'tfpay')
                    ->where('total_amount', '<', '300')
                    ->where('created_at', '>=', $time_s)
                    ->where('created_at', '<=', $time_e)
                    ->select('total_amount')
                    ->sum('total_amount');

                echo '门店ID' . $store_id;
                echo '<br>';
                echo '时间：' . $time_s . '-' . $time_e;
                echo '<br>';
                echo '300以下总交易金额：' . $total_amount;
                echo '<br>';


                //获取到收银员ID
                $MerchantStore = MerchantStore::where('store_id', $store_id)
                    ->orderBy('created_at', 'asc')
                    ->select('merchant_id')
                    ->first();

                $merchant_id = $MerchantStore->merchant_id;
                echo '收银员ID：' . $merchant_id;
                echo '<br>';

                $ActivityStoreRate = ActivityStoreRate::where('store_id', $store_id)
                    ->where('company', 'tfpay')
                    ->select('alipay')
                    ->first();

                if ($ActivityStoreRate) {
                    echo '300以下应返比例：' . $ActivityStoreRate->alipay . '%';
                    echo '<br>';
                    $get = $total_amount * 0.0038 * ($ActivityStoreRate->alipay / 100);
                    echo '300以下应返金额：' . $get;
                    echo '<br>';
                } else {

                    $get = $total_amount * 0.0038;
                    echo '300以下应返金额：' . $get;
                    echo '<br>';
                }


                //已经提现的金额
                $amount = MerchantWithdrawalsRecords::where('merchant_id', $merchant_id)
                    ->where('status', 1)
                    ->select('amount')
                    ->sum('amount');
                echo '已经提现金额：' . $amount;
                echo '<br>';


                $Merchant = Merchant::where('id', $merchant_id)
                    ->first();
                echo '商户余额：' . $Merchant->money;
                echo '<br>';
                //差额
                $money = ($get - $amount - $Merchant->money);
                echo '差额：' . $money;
                echo '<br>';
                if ($money > 0) {
                    $Merchant->money = $Merchant->money + $money;
                    $Merchant->save();
                    echo '差额补录成功：' . $Merchant->name . '-' . $Merchant->phone;
                    echo '<br>';

                } else {
                    echo '无需补录';
                }


                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                dd($e);
            }

        } catch (\Exception $exception) {
            dd($exception);
        }
    }


    // 分润账单列表
    public function commission_lists(Request $request)
    {
        try {
            $token = $this->parseToken();
            $token_user_id = $token->user_id;

            $time = $request->get('time_start', '');
            $user_id = $request->get('user_id', '');  //服务商id
            $amount_start = $request->get('amount_start', '');
            $amount_end = $request->get('amount_end', '');

            $login_user = User::where('id', $token_user_id)
                ->where('is_delete', '=', '0')
                ->first();
            if (!$login_user) {
                $this->status = '2';
                $this->message = '当前登录状态异常';
                return $this->format();
            }

            $re_data = [
                'time_start' => $time,
            ];
            $check_data = [
                'time_start' => '交易时间',
            ];
            $check = $this->check_required($re_data, $check_data);
            if ($check) {
                $this->status = '2';
                $this->message = $check;
                return $this->format();
            }

            $time_arr = explode('-', $time);
            $year = $time_arr[0];
            $month = $time_arr[1];
            $month_day = date('t', strtotime($time));
            $start_time = date('Y-m-d H:i:s', mktime(0,0,0,$month,1,$year));
            $end_time = date('Y-m-d H:i:s', mktime(23,59,59,$month,$month_day,$year));
            
            if (isset($user_id) && ($user_id != 'undefined') && $user_id) {
                if($user_id==101){
                    $user_ids = $this->getSubIds(1);
                }else{
                    $user_ids = $this->getSubIds($user_id);
                }
            } else {
                if($token_user_id==101){
                    $user_ids = $this->getSubIds(1);
                }else{
                    $user_ids = $this->getSubIds($token_user_id);
                }
            }
            $store = DB::table('stores')->where(array('ascription'=>1))->select('store_id')->get();
            $store=json_decode($store,true);
            $store_ids=[];
            foreach($store as $key=>$val){
                $store_ids[$key]=$val['store_id'];
            }

            $where = [];
            if ($amount_start) {
                $where[] = ['o.total_amount', '>=', "$amount_start"];
            }
            if ($amount_end) {
                $where[] = ['o.total_amount', '<=', "$amount_end"];
            }
            if($user_id==101 ||$token_user_id==101){
                $obj = DB::table('orders as o')->select([
                DB::raw("date_format(o.pay_time, '%Y-%m-%d') AS `modify_pay_time`"),
                'o.store_name',
                'o.company',
                'o.rate',
                DB::raw("SUM(`o`.`total_amount`) AS `total_amount`"), //交易金额
                DB::raw("SUM(`o`.`mdiscount_amount`) AS `mdiscount_amount_sum`"), //商家优惠金额
                DB::raw("u.rate AS `cost_rate`"),  //成本费率
                'o.ways_source_desc',
                'o.pay_status',
                'o.pay_status_desc',
                'o.id',
                DB::raw("COUNT(`o`.`id`) as `count_order`")
            ])
                ->leftjoin('user_rates as u', function($join){
                    $join->on('u.user_id', '=', 'o.user_id')
                        ->on('u.ways_type', '=', 'o.ways_type');
                })
                ->where($where)
                ->where('o.pay_time', '>=', "$start_time")
                ->where('o.pay_time', '<=', "$end_time")
                ->where('o.ways_type', '<>', '18888') //会员卡支付
                ->where('o.ways_type', '<>', '2005')
                ->where('o.company', '<>', 'alipay')
                ->where('o.company', '<>', 'weixin')
                ->whereNotNull('o.total_amount')
                ->whereIn('o.pay_status', ['1', '6'])
                ->whereIn('o.user_id', $user_ids)
                ->whereIn('o.store_id', $store_ids)
                ->groupBy(['modify_pay_time', 'o.store_id', 'o.company', 'o.rate', 'o.ways_source', 'o.pay_status'])
                ->orderBy('modify_pay_time', 'asc');
            }else{
                $obj = DB::table('orders as o')->select([
                DB::raw("date_format(o.pay_time, '%Y-%m-%d') AS `modify_pay_time`"),
                'o.store_name',
                'o.company',
                'o.rate',
                DB::raw("SUM(`o`.`total_amount`) AS `total_amount`"), //交易金额
                DB::raw("SUM(`o`.`mdiscount_amount`) AS `mdiscount_amount_sum`"), //商家优惠金额
                DB::raw("u.rate AS `cost_rate`"),  //成本费率
                'o.ways_source_desc',
                'o.pay_status',
                'o.pay_status_desc',
                'o.id',
                DB::raw("COUNT(`o`.`id`) as `count_order`")
            ])
                ->leftjoin('user_rates as u', function($join){
                    $join->on('u.user_id', '=', 'o.user_id')
                        ->on('u.ways_type', '=', 'o.ways_type');
                })
                ->where($where)
                ->where('o.pay_time', '>=', "$start_time")
                ->where('o.pay_time', '<=', "$end_time")
                ->where('o.ways_type', '<>', '18888') //会员卡支付
                ->where('o.ways_type', '<>', '2005')
                ->where('o.company', '<>', 'alipay')
                ->where('o.company', '<>', 'weixin')
                ->whereNotNull('o.total_amount')
                ->whereIn('o.pay_status', ['1', '6'])
                ->whereIn('o.user_id', $user_ids)
                ->groupBy(['modify_pay_time', 'o.store_id', 'o.company', 'o.rate', 'o.ways_source', 'o.pay_status'])
                ->orderBy('modify_pay_time', 'asc');
            }

            $this->t = count($obj->get()->toArray());
            $data = $this->page($obj)->get();

        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage().'-'.$exception->getLine();
            return $this->format();
        }

        $this->status = '1';
        $this->message = '数据返回成功';
        return $this->format($data);
    }

    private function getAgentSubId($id, &$agent_list)
    {
        $array = [];
        if ($agent_list) {
            foreach ($agent_list as $_id => $pid) {
                if ($pid == $id) {
                    $array[] = $_id;
                    $_array = $this->getAgentSubId($_id, $agent_list);
                    if (is_array($_array)) {
                        $array = array_merge($array, $_array);
                    }
                }
            }
        }
        return $array;
    }

    private function getMonthDifference($start, $end)
    {
        $years = date('Y', $end) - date('Y', $start);
        $monthTotal = $years * 12 + date('m', $end) - date('m', $start);
        return $monthTotal;
    }

    public function commission_count(Request $request){
        $format = [];
        $curHdIndex = $request->get('curHdIndex', '');
        $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
        $date_start = $request->get('start_date', $request->get('start_data', ''));
        $date_end = $request->get('end_date', $request->get('end_data', ''));
        try {
            $login_user = User::where('id', $user_id)->where('is_delete', '=', '0')->first();
            if (!$login_user) {
               throw new \Exception("登录异常");
            }
            
            
            $curHdTit = '';
            switch (intval($curHdIndex)) {
                case 1://今日
                    $date_start = date('Y-m-d 00:00:00');
                    $date_end = date('Y-m-d 23:59:59');
                    $curHdTit = '今日';
                    break;
                case 2://昨日
                    $date_start = date('Y-m-d 00:00:00', strtotime("-1 day"));
                    $date_end = date('Y-m-d 23:59:59', strtotime("-1 day"));
                    $curHdTit = '昨日';
                    break;
                case 3://上周
                    $date_start = date('Y-m-d 00:00:00', strtotime('last week'));
                    $date_end = date('Y-m-d 23:59:59', strtotime('this week -1 day'));
                    $curHdTit = '上周';
                    break;
                case 4://本月
                    $date_start = date('Y-m-01 00:00:00');
                    $date_end = date('Y-m-t 23:59:59');
                    $curHdTit = '本月';
                    break;
                case 5://上月
                    $date_start = date('Y-m-01 00:00:00', strtotime('-1 month', time()));
                    $date_end = date('Y-m-t 23:59:59', strtotime('-1 month', time()));
                    $curHdTit = '上月';
                    break;
            }
            $time_end = strtotime($date_end);
            $time_start = strtotime($date_start);
            if ($time_end<$date_start){
                throw new \Exception("结束时间不能大于开始时间");
            }
            if ($time_start<strtotime('2023-06-01')){
                throw new \Exception("查询最小时间不能低于2023-06-01");
            }
            if ($time_end>strtotime(date('Y-m-t 23:59:59'))){
                throw new \Exception("查询最大时间不能高于当天");
            }
            $cache_key = 'agent:sub_list';
            $db = DB::connection();
            $agentSubList = Cache::get($cache_key,false);
            if ($agentSubList == false) {
                $agentSubList = [];
                $agentList = $db->table('users')->pluck('pid', 'id');
                foreach ($agentList as $_id => $pid) {
                    $agentSubList[$_id] = $this->getAgentSubId($_id, $agentList);
                }
                if (is_array($agentSubList) && count($agentSubList) > 0) {
                    Cache::add($cache_key, $agentSubList, 120);
                }
            }
            $total_amount = '0.00';
            $total_num = '0';
            $weixin_total_amount = '0.00';
            $alipay_total_amount = '0.00';
            $unionpay_total_amount = '0.00';
            $bestpay_total_amount = '0.00';
            $pos_total_amount = '0.00';
            $commission_money = '0.00';
            $addstores = 0;
            $user_rates = $db->table('user_rates')->where('user_id', $user_id)->distinct('company')->pluck(DB::raw("CONCAT(server_rate,':',era_rate,':',rate,':',yu_rate)"), 'company')->toArray();
            $company_list = $db->table('store_all_pay_way_lists')->whereIn('company', array_keys($user_rates))->pluck('company_desc', 'company')->toArray();
            $user_company = $db->table('user_rates')->where('user_id', $user_id)->groupBy('company')->pluck(DB::raw("GROUP_CONCAT(ways_type)"), 'company')->toArray();
            $user_company_method = $db->table('store_ways_desc')->whereIn('company', array_keys($user_rates))->pluck(DB::raw("CONCAT(ways_desc,':',ways_source)"), 'ways_type')->toArray();
            if (is_array($user_rates)) {
                $monthTotal = $this->getMonthDifference(strtotime($date_start), strtotime($date_end));
               
                $agentIds = array_merge($agentSubList[$user_id], [$user_id]);
                $addstores = $db->table('stores')->where('pid', 0)->whereIn('user_id', $agentIds)->whereBetween('created_at', [$date_start, $date_end])->count('store_id');
                foreach ($user_company as $company => $ways_type) {
                    if(!isset($company_list[$company])){
                         continue;
                    }
                    $company_name = $company_list[$company];
                    $company_rates = explode(':', $user_rates[$company]);
                    $explode = explode(',', $ways_type);
                    $tableName = 'wft_stores_orders_' . date('Ym', strtotime($date_start)) . '_bill';
                     //error_log(date('Y-m-d H:i:s')." 【对账调试】： ".json_encode([$tableName])."\n\n", 3, "/www/wwwlogs/wft/". 'prod-easy-pay'.date('Ymd').".log");
                    $pluck = DB::connection('old_mysql')->table($tableName)
                        ->whereIn('receive_code', $explode)
                        ->whereIn('sales_id', $agentIds)
                        ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                        ->select([
                            'receive_code',
                            'receive_rate',
                            'receive_model',
                            DB::raw('sum(receive_fee) as receive_fee'),
                            DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                            DB::raw('sum(order_total) as order_total'),
                            DB::raw('sum(order_amount) as order_amount'),
                            DB::raw('sum(refund_total) as refund_total'),
                            DB::raw('sum(refund_amount) as refund_amount'),
                        ])
                        ->groupBy(Db::raw('receive_code,receive_rate,receive_model'));
                         //error_log(date('Y-m-d H:i:s')." 【对账调试】： ".json_encode([$user_id,$agentIds,$tableName,$explode,$agentIds,$date_start,$date_end])."\n\n", 3, "/www/wwwlogs/wft/". 'prod-easy-pay'.date('Ymd').".log");

                    for ($i = 0; $i < $monthTotal; $i++) {
                        $num = $i + 1;
                        $numTime = strtotime("+" . $num . " month", strtotime($date_start));
                        $tableName = 'wft_stores_orders_' . date('Ym', $numTime) . '_bill';
                        //error_log(date('Y-m-d H:i:s')." 【对账调试】： ".json_encode([$tableName])."\n\n", 3, "/www/wwwlogs/wft/". 'prod-easy-pay'.date('Ymd').".log");

                        $union_pluck = DB::connection('old_mysql')->table($tableName)
                            ->whereIn('receive_code', $explode)
                            ->whereIn('sales_id', $agentIds)
                            ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                            ->select([
                                'receive_code',
                                'receive_rate',
                                'receive_model',
                                DB::raw('sum(receive_fee) as receive_fee'),
                                DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                                DB::raw('sum(order_total) as order_total'),
                                DB::raw('sum(order_amount) as order_amount'),
                                DB::raw('sum(refund_total) as refund_total'),
                                DB::raw('sum(refund_amount) as refund_amount'),
                            ])
                            ->groupBy(Db::raw('receive_code,receive_rate,receive_model'));
                        $pluck->unionAll($union_pluck);
                    }

                    foreach ($pluck->get() as $obj) {
                        $item = (array)$obj;
                        $user_rate = $company_rates[$item['receive_model'] - 1];
                        $company_method = $user_company_method[$item['receive_code']];
                        $company_method_explode = explode(':', $company_method);
                        //if ($user_rate > 0 && $item['receive_rate'] > $user_rate) {
                            $difference = bcmul(bcdiv(bcsub($item['receive_rate'], $user_rate, 2), 100, 4), bcsub($item['order_amount'], $item['refund_amount']), 2);
                            $difference = bcdiv($difference, 100, 2);
                            $commission_money = bcadd($commission_money, $difference, 2);
                        //}
                        $total_amount = bcadd($total_amount, bcdiv($item['order_amount'], 100, 2), 2);
                        $total_num = bcadd($total_num, $item['order_total']);
                        switch ($company_method_explode[1]) {
                            case 'alipay':
                                $alipay_total_amount = bcadd($alipay_total_amount, bcdiv($item['order_amount'], 100, 2), 2);
                                break;
                            case 'weixin':
                                $weixin_total_amount = bcadd($weixin_total_amount, bcdiv($item['order_amount'], 100, 2), 2);
                                break;
                            case 'Bestpay':
                                $bestpay_total_amount = bcadd($bestpay_total_amount, bcdiv($item['order_amount'], 100, 2), 2);
                                break;
                            case 'unionpay':
                                $unionpay_total_amount = bcadd($unionpay_total_amount, bcdiv($item['order_amount'], 100, 2), 2);
                                break;
                        }

                    }
                }
            }
            $format = [
                'date' => $curHdTit,
                'total_amount' => $total_amount,
                'total_num' => $total_num,
                'weixin_total_amount' => $weixin_total_amount,
                'alipay_total_amount' => $alipay_total_amount,
                'unionpay_total_amount' => $unionpay_total_amount,
                'Bestpay_total_amount' => $bestpay_total_amount,
                'pos_total_amount' => $pos_total_amount,
                'commission_money' => $commission_money,
                'addstores' => $addstores,
            ];
            $this->status = 1;
            $this->message = 'Ok';
        } catch (\Exception $e) {
            $this->status = 2;
            $this->message = $e->getMessage();
        }
        return $this->format($format);
    }

    //计算代理商分佣
    public function _commission_count(Request $request)
    {
        $token = $this->parseToken();
        $token_user_id = $token->user_id;
        $curHdIndex=$request->get('curHdIndex', '');
        $start_data=$request->get('start_data', '');
        $end_data=$request->get('end_data', '');

        $login_user = User::where('id', $token_user_id)
            ->where('is_delete', '=', '0')
            ->first();
        if (!$login_user) {
            $this->status = '2';
            $this->message = '当前登录状态异常';
            return $this->format();
        }
        $user_ids = $this->getSubIds($token_user_id);
        $store_ids=DB::table('stores')->whereIn('user_id', $user_ids)->select('store_id')->get();
        $store_ids=json_decode($store_ids,true);
        foreach($store_ids as $k=>$v){
            $store_data[$k]=$v['store_id'];
        }
        $table1='wft_stores_orders_202307_bill';
        $table2='wft_stores_orders_202306_bill';
        
        if($token_user_id=='347'){
            $pingan_stores=DB::table('pingan_stores')->where('type', 1)->select('store_id')->get();
            $store_ids=[];
            foreach ($pingan_stores as $k=>$v){
                $store_ids[$k]=$v->store_id;
            }
            if($curHdIndex ==1){
            $where[] = ['created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
            $where[] = ['created_at', '<=', date('Y-m-d', time()).' 23:59:59'];
            //总收款
            $total_amount=Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
            //总收款笔数
            $total_num=count(Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->get());
            //微信收款总额
            $weixin_total_amount = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'weixin')->select('total_amount')->sum('total_amount');
            //支付宝收款金额
            $alipay_total_amount = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'alipay')->select('total_amount')->sum('total_amount');
            // 云闪付收款金额
            $unionpay_total_amount = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'unionpay')->select('total_amount')->sum('total_amount');
            // 翼支付收款金额
            $Bestpay_total_amount = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'Bestpay')->select('total_amount')->sum('total_amount');
            // pos支付
            $pos_total_amount = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'unionpay')->select('total_amount')->where('ways_type_desc', '刷卡支付')->select('total_amount')->sum('total_amount');
            $addstores=Store::whereIn('store_id', $store_ids)->where($where)->select('store_id')->count('store_id');
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_num'=>$total_num,
                'weixin_total_amount'=>$weixin_total_amount,
                'alipay_total_amount'=>$alipay_total_amount,
                'unionpay_total_amount'=>$unionpay_total_amount,
                'Bestpay_total_amount'=>$Bestpay_total_amount,
                'pos_total_amount'=>$pos_total_amount,
                'commission_money'=>'未结算',
                'addstores'=>$addstores,
                'date'=>'今日'
                );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==2){
            $where[] = ['settling_day', '>=', date('Y-m-d',strtotime("-1 day"))];
            $where[] = ['settling_day', '<=', date('Y-m-d',strtotime("-1 day"))];
            //总收款
            $total_amount=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where('user_id', 1)->where($where)->select('total_amount')->sum('total_amount');
            //总收款笔数
            $total_num=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where('user_id', 1)->where($where)->select('total_num')->sum('total_num');
            //微信收款总额
            $weixin_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('weixin_amount')->sum('weixin_amount');;
            //支付宝收款金额
            $alipay_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('alipay_amount')->sum('alipay_amount');;
            // 云闪付收款金额
            $unionpay_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('unionpay_amount')->sum('unionpay_amount');;
            // 翼支付收款金额
            $Bestpay_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('Bestpay_amount')->sum('Bestpay_amount');;
            // pos支付
//            $pos_total_amount = Order::whereIn('user_id', $user_ids)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'Bestpay')->select('total_amount')->sum('total_amount');
            $commission_money=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            $pos_total_amount=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where($where)->where('user_id',$token_user_id)->select('shuaka_amount')->sum('shuaka_amount');
            $where1[] = ['created_at', '>=', date('Y-m-d',strtotime("-1 day")).' 00:00:00'];
            $where1[] = ['created_at', '<=', date('Y-m-d',strtotime("-1 day")).' 23:59:59'];
            $addstores=Store::whereIn('store_id', $store_ids)->where($where1)->select('store_id')->count('store_id');
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_num'=>$total_num,
                'weixin_total_amount'=>$weixin_total_amount,
                'alipay_total_amount'=>$alipay_total_amount,
                'unionpay_total_amount'=>$unionpay_total_amount,
                'Bestpay_total_amount'=>$Bestpay_total_amount,
                'pos_total_amount'=>$pos_total_amount,
                'commission_money'=>$commission_money,
                'addstores'=>$addstores,
                'date'=>'昨日'
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==3){
            $where[] = ['settling_day', '>=', date('Y-m-d', strtotime('last week'))];
            $where[] = ['settling_day', '<=', date('Y-m-d', strtotime('this week -1 day'))];
            //总收款
            $total_amount=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where('user_id', 1)->where($where)->select('total_amount')->sum('total_amount');
            //总收款笔数
            $total_num=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where('user_id', 1)->where($where)->select('total_num')->sum('total_num');
            //微信收款总额
            $weixin_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('weixin_amount')->sum('weixin_amount');;
            //支付宝收款金额
            $alipay_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('alipay_amount')->sum('alipay_amount');;
            // 云闪付收款金额
            $unionpay_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('unionpay_amount')->sum('unionpay_amount');;
            // 翼支付收款金额
            $Bestpay_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('Bestpay_amount')->sum('Bestpay_amount');;
            // pos支付
//            $pos_total_amount = Order::whereIn('user_id', $user_ids)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'Bestpay')->select('total_amount')->sum('total_amount');
            $pos_total_amount=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where($where)->where('user_id',$token_user_id)->select('shuaka_amount')->sum('shuaka_amount');
            $commission_money=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            $where1[] = ['created_at', '>=', date('Y-m-d', strtotime('last week')).' 00:00:00'];
            $where1[] = ['created_at', '<=', date('Y-m-d', strtotime('this week -1 day')).' 23:59:59'];
            $addstores=Store::whereIn('store_id', $store_ids)->where($where1)->select('store_id')->count('store_id');
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_num'=>$total_num,
                'weixin_total_amount'=>$weixin_total_amount,
                'alipay_total_amount'=>$alipay_total_amount,
                'unionpay_total_amount'=>$unionpay_total_amount,
                'Bestpay_total_amount'=>$Bestpay_total_amount,
                'pos_total_amount'=>$pos_total_amount,
                'commission_money'=>$commission_money,
                'addstores'=>$addstores,
                'date'=>'上周'
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==4){
            $where[] = ['settling_day', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
            $where[] = ['settling_day', '<=', date('Y-m-d',strtotime("-1 day"))];
            //总收款
            $total_amount=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where('user_id', 1)->where($where)->select('total_amount')->sum('total_amount');
            //总收款笔数
            $total_num=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where('user_id', 1)->where($where)->select('total_num')->sum('total_num');
            //微信收款总额
            $weixin_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('weixin_amount')->sum('weixin_amount');;
            //支付宝收款金额
            $alipay_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('alipay_amount')->sum('alipay_amount');;
            // 云闪付收款金额
            $unionpay_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('unionpay_amount')->sum('unionpay_amount');;
            // 翼支付收款金额
            $Bestpay_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('Bestpay_amount')->sum('Bestpay_amount');;
            // pos支付
//            $pos_total_amount = Order::whereIn('user_id', $user_ids)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'Bestpay')->select('total_amount')->sum('total_amount');
            $pos_total_amount=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where($where)->where('user_id',$token_user_id)->select('shuaka_amount')->sum('shuaka_amount');
            $commission_money=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            $where1[] = ['created_at', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00')).' 00:00:00'];
            $where1[] = ['created_at', '<=', date('Y-m-d',strtotime("-1 day")).' 23:59:59'];
            $addstores=Store::whereIn('store_id', $store_ids)->where($where1)->select('store_id')->count('store_id');
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_num'=>$total_num,
                'weixin_total_amount'=>$weixin_total_amount,
                'alipay_total_amount'=>$alipay_total_amount,
                'unionpay_total_amount'=>$unionpay_total_amount,
                'Bestpay_total_amount'=>$Bestpay_total_amount,
                'pos_total_amount'=>$pos_total_amount,
                'commission_money'=>$commission_money,
                'addstores'=>$addstores,
                'date'=>'本月'
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==5){
            $hdate=date('d',time());
            if($hdate=='31'){
              $where[] = ['settling_day', '>=', date('Y-m-01', strtotime('-31 day'))];
              $where[] = ['settling_day', '<=', date('Y-m-t', strtotime('-31 day'))];
            }else{
              $where[] = ['settling_day', '>=', date('Y-m-01', strtotime('-1 month'))];
              $where[] = ['settling_day', '<=', date('Y-m-t', strtotime('-1 month'))];
            }
            //总收款
            $total_amount=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where('user_id', 1)->where($where)->select('total_amount')->sum('total_amount');
            //总收款笔数
            $total_num=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where('user_id', 1)->where($where)->select('total_num')->sum('total_num');
            //微信收款总额
            $weixin_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('weixin_amount')->sum('weixin_amount');;
            //支付宝收款金额
            $alipay_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('alipay_amount')->sum('alipay_amount');;
            // 云闪付收款金额
            $unionpay_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('unionpay_amount')->sum('unionpay_amount');;
            // 翼支付收款金额
            $Bestpay_total_amount=DB::table('stores_day_count')->whereIn('store_id', $store_ids)->where($where)->select('Bestpay_amount')->sum('Bestpay_amount');;
            // pos支付
//            $pos_total_amount = Order::whereIn('user_id', $user_ids)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'Bestpay')->select('total_amount')->sum('total_amount');
            $pos_total_amount=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where($where)->where('user_id',$token_user_id)->select('shuaka_amount')->sum('shuaka_amount');
            $commission_money=DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            $where1[] = ['created_at', '>=', date('Y-m-01', strtotime('-1 month')).' 00:00:00'];
            $where1[] = ['created_at', '<=', date('Y-m-t', strtotime('-1 month')).' 23:59:59'];
            $addstores=Store::whereIn('store_id', $store_ids)->where($where1)->select('store_id')->count('store_id');
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_num'=>$total_num,
                'weixin_total_amount'=>$weixin_total_amount,
                'alipay_total_amount'=>$alipay_total_amount,
                'unionpay_total_amount'=>$unionpay_total_amount,
                'Bestpay_total_amount'=>$Bestpay_total_amount,
                'pos_total_amount'=>$pos_total_amount,
                'commission_money'=>$commission_money,
                'addstores'=>$addstores,
                'date'=>'上月'
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }
        }else{
            if($curHdIndex ==1){
            $where[] = ['created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
            $where[] = ['created_at', '<=', date('Y-m-d', time()).' 23:59:59'];
            //总收款

            $total_amount=Order::whereIn('user_id', $user_ids)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
            //总收款笔数
            $total_num=count(Order::whereIn('user_id', $user_ids)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->get());
            //微信收款总额
            $weixin_total_amount = Order::whereIn('user_id', $user_ids)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'weixin')->select('total_amount')->sum('total_amount');
            //支付宝收款金额
            $alipay_total_amount = Order::whereIn('user_id', $user_ids)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'alipay')->select('total_amount')->sum('total_amount');
            // 云闪付收款金额
            $unionpay_total_amount = Order::whereIn('user_id', $user_ids)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'unionpay')->select('total_amount')->sum('total_amount');
            // 翼支付收款金额
            $Bestpay_total_amount = Order::whereIn('user_id', $user_ids)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'Bestpay')->select('total_amount')->sum('total_amount');
            // pos支付
            $pos_total_amount = Order::whereIn('user_id', $user_ids)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'unionpay')->select('total_amount')->where('ways_type_desc', '刷卡支付')->select('total_amount')->sum('total_amount');
            $addstores=Store::whereIn('user_id', $user_ids)->where($where)->select('store_id')->count('store_id');
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_num'=>$total_num,
                'weixin_total_amount'=>$weixin_total_amount,
                'alipay_total_amount'=>$alipay_total_amount,
                'unionpay_total_amount'=>$unionpay_total_amount,
                'Bestpay_total_amount'=>$Bestpay_total_amount,
                'pos_total_amount'=>$pos_total_amount,
                'commission_money'=>'未结算',
                'addstores'=>$addstores,
                'date'=>'今日'
                );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==2){
            $where[] = ['bill_date', '>=', strtotime('yesterday')];
            $where[] = ['bill_date', '<=', strtotime('yesterday')+86399];
            $start_date=date('Y-m-d',strtotime("-1 day"));
            $end_date=date('Y-m-d',strtotime("-1 day"));
            //总收款
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $total_amount += $obj->order_amount;
                }
                $total_amount=$total_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
                
                $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_total']);
                $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_total']);
                $order_total_zong->unionAll($order_total_zong1);
                $order_total=0;
                foreach ($order_total_zong->get() as $obj) {
                    $order_total += $obj->order_total;
                }
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
                $order_total=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_total')->sum('order_total');
            }
            $total_amount=bcsub($total_amount,$refund_amount,2);
            //总收款笔数
            $total_num=$order_total;
            
            //微信收款总额
            $ways_weixin=DB::table('store_ways_desc')->where('ways_source', 'weixin')->select('ways_type as receive_code')->distinct()->get();
            $ways_weixin=json_decode($ways_weixin,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_weixin)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_weixin)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $weixin_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $weixin_total_amount += $obj->order_amount;
                }
                $weixin_total_amount=$weixin_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $weixin_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_weixin)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            //支付宝收款金额
            $ways_alipay=DB::table('store_ways_desc')->where('ways_source', 'alipay')->select('ways_type as receive_code')->distinct()->get();
            $ways_alipay=json_decode($ways_alipay,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_alipay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_alipay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $alipay_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $alipay_total_amount += $obj->order_amount;
                }
                $alipay_total_amount=$alipay_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $alipay_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_alipay)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            // 云闪付收款金额
            $ways_unionpay=DB::table('store_ways_desc')->where('ways_source', 'unionpay')->select('ways_type as receive_code')->distinct()->get();
            $ways_unionpay=json_decode($ways_unionpay,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_unionpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_unionpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $unionpay_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $unionpay_total_amount += $obj->order_amount;
                }
                $unionpay_total_amount=$unionpay_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $unionpay_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_unionpay)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            //翼支付收款金额
            $ways_wingpay=DB::table('store_ways_desc')->where('ways_source', 'Bestpay')->select('ways_type as receive_code')->distinct()->get();
            $ways_wingpay=json_decode($ways_wingpay,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_wingpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_wingpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $Bestpay_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $Bestpay_total_amount += $obj->order_amount;
                }
                $Bestpay_total_amount=$Bestpay_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $Bestpay_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_wingpay)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            $where_c[] = ['settling_day', '>=', date('Y-m-d',strtotime("-1 day"))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d',strtotime("-1 day"))];
            $commission_money=DB::table('company_day_commission')->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            
            $pos_total_amount=0.00;

            $where1[] = ['created_at', '>=', date('Y-m-d',strtotime("-1 day")).' 00:00:00'];
            $where1[] = ['created_at', '<=', date('Y-m-d',strtotime("-1 day")).' 23:59:59'];
            $addstores=Store::whereIn('user_id', $user_ids)->where($where1)->select('store_id')->count('store_id');
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_num'=>$total_num,
                'weixin_total_amount'=>$weixin_total_amount,
                'alipay_total_amount'=>$alipay_total_amount,
                'unionpay_total_amount'=>$unionpay_total_amount,
                'Bestpay_total_amount'=>$Bestpay_total_amount,
                'pos_total_amount'=>$pos_total_amount,
                'commission_money'=>$commission_money,
                'addstores'=>$addstores,
                'date'=>'昨日'
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==3){
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'))];
            $start_date=date('Y-m-d', strtotime('last week'));
            $end_date=date('Y-m-d', strtotime('this week -1 day'));
            //总收款
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $total_amount += $obj->order_amount;
                }
                $total_amount=$total_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
                
                $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_total']);
                $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_total']);
                $order_total_zong->unionAll($order_total_zong1);
                $order_total=0;
                foreach ($order_total_zong->get() as $obj) {
                    $order_total += $obj->order_total;
                }
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
                $order_total=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_total')->sum('order_total');
            }
            $total_amount=bcsub($total_amount,$refund_amount,2);
            //总收款笔数
            $total_num=$order_total;
            
            //微信收款总额
            $ways_weixin=DB::table('store_ways_desc')->where('ways_source', 'weixin')->select('ways_type as receive_code')->distinct()->get();
            $ways_weixin=json_decode($ways_weixin,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_weixin)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_weixin)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $weixin_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $weixin_total_amount += $obj->order_amount;
                }
                $weixin_total_amount=$weixin_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $weixin_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_weixin)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            //支付宝收款金额
            $ways_alipay=DB::table('store_ways_desc')->where('ways_source', 'alipay')->select('ways_type as receive_code')->distinct()->get();
            $ways_alipay=json_decode($ways_alipay,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_alipay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_alipay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $alipay_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $alipay_total_amount += $obj->order_amount;
                }
                $alipay_total_amount=$alipay_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $alipay_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_alipay)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            // 云闪付收款金额
            $ways_unionpay=DB::table('store_ways_desc')->where('ways_source', 'unionpay')->select('ways_type as receive_code')->distinct()->get();
            $ways_unionpay=json_decode($ways_unionpay,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_unionpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_unionpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $unionpay_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $unionpay_total_amount += $obj->order_amount;
                }
                $unionpay_total_amount=$unionpay_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $unionpay_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_unionpay)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            //翼支付收款金额
            $ways_wingpay=DB::table('store_ways_desc')->where('ways_source', 'Bestpay')->select('ways_type as receive_code')->distinct()->get();
            $ways_wingpay=json_decode($ways_wingpay,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_wingpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_wingpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $Bestpay_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $Bestpay_total_amount += $obj->order_amount;
                }
                $Bestpay_total_amount=$Bestpay_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $Bestpay_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_wingpay)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime('last week'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime('this week -1 day'))];
            $commission_money=DB::table('company_day_commission')->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            
            $pos_total_amount=0.00;
            $where1[] = ['created_at', '>=', date('Y-m-d', strtotime('last week')).' 00:00:00'];
            $where1[] = ['created_at', '<=', date('Y-m-d', strtotime('this week -1 day')).' 23:59:59'];
            $addstores=Store::whereIn('user_id', $user_ids)->where($where1)->select('store_id')->count('store_id');
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_num'=>$total_num,
                'weixin_total_amount'=>$weixin_total_amount,
                'alipay_total_amount'=>$alipay_total_amount,
                'unionpay_total_amount'=>$unionpay_total_amount,
                'Bestpay_total_amount'=>$Bestpay_total_amount,
                'pos_total_amount'=>$pos_total_amount,
                'commission_money'=>$commission_money,
                'addstores'=>$addstores,
                'date'=>'上周'
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==4){
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),1,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(0,0,0,date('m'),date('d'),date('Y'))-1];
            $start_date=date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'));
            $end_date=date('Y-m-d',strtotime("-1 day"));
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $total_amount += $obj->order_amount;
                }
                $total_amount=$total_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
                
                $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_total']);
                $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_total']);
                $order_total_zong->unionAll($order_total_zong1);
                $order_total=0;
                foreach ($order_total_zong->get() as $obj) {
                    $order_total += $obj->order_total;
                }
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
                $order_total=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_total')->sum('order_total');
            }
            $total_amount=bcsub($total_amount,$refund_amount,2);
            //总收款笔数
            $total_num=$order_total;
            
            //微信收款总额
            $ways_weixin=DB::table('store_ways_desc')->where('ways_source', 'weixin')->select('ways_type as receive_code')->distinct()->get();
            $ways_weixin=json_decode($ways_weixin,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_weixin)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_weixin)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $weixin_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $weixin_total_amount += $obj->order_amount;
                }
                $weixin_total_amount=$weixin_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $weixin_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_weixin)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            //支付宝收款金额
            $ways_alipay=DB::table('store_ways_desc')->where('ways_source', 'alipay')->select('ways_type as receive_code')->distinct()->get();
            $ways_alipay=json_decode($ways_alipay,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_alipay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_alipay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $alipay_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $alipay_total_amount += $obj->order_amount;
                }
                $alipay_total_amount=$alipay_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $alipay_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_alipay)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            // 云闪付收款金额
            $ways_unionpay=DB::table('store_ways_desc')->where('ways_source', 'unionpay')->select('ways_type as receive_code')->distinct()->get();
            $ways_unionpay=json_decode($ways_unionpay,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_unionpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_unionpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $unionpay_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $unionpay_total_amount += $obj->order_amount;
                }
                $unionpay_total_amount=$unionpay_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $unionpay_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_unionpay)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            //翼支付收款金额
            $ways_wingpay=DB::table('store_ways_desc')->where('ways_source', 'Bestpay')->select('ways_type as receive_code')->distinct()->get();
            $ways_wingpay=json_decode($ways_wingpay,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_wingpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_wingpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $Bestpay_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $Bestpay_total_amount += $obj->order_amount;
                }
                $Bestpay_total_amount=$Bestpay_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $Bestpay_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_wingpay)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d',strtotime("-1 day"))];
            $commission_money=$commission_money=DB::table('company_day_commission')->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            
            $pos_total_amount=0.00;
            $where1[] = ['created_at', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00')).' 00:00:00'];
            $where1[] = ['created_at', '<=', date('Y-m-d',strtotime("-1 day")).' 23:59:59'];
            $addstores=Store::whereIn('user_id', $user_ids)->where($where1)->select('store_id')->count('store_id');
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_num'=>$total_num,
                'weixin_total_amount'=>$weixin_total_amount,
                'alipay_total_amount'=>$alipay_total_amount,
                'unionpay_total_amount'=>$unionpay_total_amount,
                'Bestpay_total_amount'=>$Bestpay_total_amount,
                'pos_total_amount'=>$pos_total_amount,
                'commission_money'=>$commission_money,
                'addstores'=>$addstores,
                'date'=>'本月'
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==5){
            $where[] = ['bill_date', '>=', strtotime(date('Y-m-01 00:00:00',strtotime(date('Y-m-01') . " - 1 month")))];
            $where[] = ['bill_date', '<=', strtotime(date("Y-m-d 23:59:59", strtotime(-date('d').'day')))];
            $start_date=date('Y-m-01',strtotime(date('Y-m-01') . " - 1 month"));
            $end_date=date("Y-m-d", strtotime(-date('d').'day'));
            
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $total_amount += $obj->order_amount;
                }
                $total_amount=$total_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
                
                $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_total']);
                $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_total']);
                $order_total_zong->unionAll($order_total_zong1);
                $order_total=0;
                foreach ($order_total_zong->get() as $obj) {
                    $order_total += $obj->order_total;
                }
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
                $order_total=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_total')->sum('order_total');
            }
            $total_amount=bcsub($total_amount,$refund_amount,2);
            //总收款笔数
            $total_num=$order_total;
            
            //微信收款总额
            $ways_weixin=DB::table('store_ways_desc')->where('ways_source', 'weixin')->select('ways_type as receive_code')->distinct()->get();
            $ways_weixin=json_decode($ways_weixin,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_weixin)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_weixin)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $weixin_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $weixin_total_amount += $obj->order_amount;
                }
                $weixin_total_amount=$weixin_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $weixin_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_weixin)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            //支付宝收款金额
            $ways_alipay=DB::table('store_ways_desc')->where('ways_source', 'alipay')->select('ways_type as receive_code')->distinct()->get();
            $ways_alipay=json_decode($ways_alipay,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_alipay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_alipay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $alipay_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $alipay_total_amount += $obj->order_amount;
                }
                $alipay_total_amount=$alipay_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $alipay_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_alipay)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            // 云闪付收款金额
            $ways_unionpay=DB::table('store_ways_desc')->where('ways_source', 'unionpay')->select('ways_type as receive_code')->distinct()->get();
            $ways_unionpay=json_decode($ways_unionpay,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_unionpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_unionpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $unionpay_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $unionpay_total_amount += $obj->order_amount;
                }
                $unionpay_total_amount=$unionpay_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $unionpay_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_unionpay)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            //翼支付收款金额
            $ways_wingpay=DB::table('store_ways_desc')->where('ways_source', 'Bestpay')->select('ways_type as receive_code')->distinct()->get();
            $ways_wingpay=json_decode($ways_wingpay,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_wingpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_wingpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $Bestpay_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $Bestpay_total_amount += $obj->order_amount;
                }
                $Bestpay_total_amount=$Bestpay_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $Bestpay_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_wingpay)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            
            $hdate=date('d',time());
            if($hdate=='31'){
              $where_c[] = ['settling_day', '>=', date('Y-m-01', strtotime('-31 day'))];
              $where_c[] = ['settling_day', '<=', date('Y-m-t', strtotime('-31 day'))];
            }else{
              $where_c[] = ['settling_day', '>=', date('Y-m-01', strtotime('-1 month'))];
              $where_c[] = ['settling_day', '<=', date('Y-m-t', strtotime('-1 month'))];
            }
            $commission_money=DB::table('company_day_commission')->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            
            $pos_total_amount=0.00;
            $where1[] = ['created_at', '>=', date('Y-m-01', strtotime('-1 month')).' 00:00:00'];
            $where1[] = ['created_at', '<=', date('Y-m-t', strtotime('-1 month')).' 23:59:59'];
            $addstores=Store::whereIn('user_id', $user_ids)->where($where1)->select('store_id')->count('store_id');
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_num'=>$total_num,
                'weixin_total_amount'=>$weixin_total_amount,
                'alipay_total_amount'=>$alipay_total_amount,
                'unionpay_total_amount'=>$unionpay_total_amount,
                'Bestpay_total_amount'=>$Bestpay_total_amount,
                'pos_total_amount'=>$pos_total_amount,
                'commission_money'=>$commission_money,
                'addstores'=>$addstores,
                'date'=>'上月'
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==6){
            $where[] = ['bill_date', '>=', strtotime($start_data.' 00:00:00')];
            $where[] = ['bill_date', '<=', strtotime($end_data.' 23:59:59')];
            $start_date=$start_data;
            $end_date=$end_data;
            //总收款
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $total_amount += $obj->order_amount;
                }
                $total_amount=$total_amount/100;
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
                
                $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_total']);
                $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_total']);
                $order_total_zong->unionAll($order_total_zong1);
                $order_total=0;
                foreach ($order_total_zong->get() as $obj) {
                    $order_total += $obj->order_total;
                }
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
                $order_total=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_total')->sum('order_total');
            }
            $total_amount=bcsub($total_amount,$refund_amount,2);
            //总收款笔数
            $total_num=$order_total;
            //微信收款总额
            $ways_weixin=DB::table('store_ways_desc')->where('ways_source', 'weixin')->select('ways_type as receive_code')->distinct()->get();
            $ways_weixin=json_decode($ways_weixin,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_weixin)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_weixin)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $weixin_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $weixin_total_amount += $obj->order_amount;
                }
                $weixin_total_amount=$weixin_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $weixin_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_weixin)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            //支付宝收款金额
            $ways_alipay=DB::table('store_ways_desc')->where('ways_source', 'alipay')->select('ways_type as receive_code')->distinct()->get();
            $ways_alipay=json_decode($ways_alipay,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_alipay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_alipay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $alipay_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $alipay_total_amount += $obj->order_amount;
                }
                $alipay_total_amount=$alipay_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $alipay_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_alipay)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            // 云闪付收款金额
            $ways_unionpay=DB::table('store_ways_desc')->where('ways_source', 'unionpay')->select('ways_type as receive_code')->distinct()->get();
            $ways_unionpay=json_decode($ways_unionpay,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_unionpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_unionpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $unionpay_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $unionpay_total_amount += $obj->order_amount;
                }
                $unionpay_total_amount=$unionpay_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $unionpay_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_unionpay)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            //翼支付收款金额
            $ways_wingpay=DB::table('store_ways_desc')->where('ways_source', 'Bestpay')->select('ways_type as receive_code')->distinct()->get();
            $ways_wingpay=json_decode($ways_wingpay,true);
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_wingpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$ways_wingpay)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $Bestpay_total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $Bestpay_total_amount += $obj->order_amount;
                }
                $Bestpay_total_amount=$Bestpay_total_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $Bestpay_total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$ways_wingpay)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            }
            
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            
            $where_c[] = ['settling_day', '>=', $start_date];
            $where_c[] = ['settling_day', '<=', $end_date];
            $commission_money=DB::table('company_day_commission')->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            // $commission_money=$this->get_commission($token_user_id,$get_commission);
            $pos_total_amount=0.00;
            $where1[] = ['created_at', '>=', $start_data.' 00:00:00'];
            $where1[] = ['created_at', '<=', $end_data.' 23:59:59'];
            $addstores=Store::whereIn('user_id', $user_ids)->where($where1)->select('store_id')->count('store_id');
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_num'=>$total_num,
                'weixin_total_amount'=>$weixin_total_amount,
                'alipay_total_amount'=>$alipay_total_amount,
                'unionpay_total_amount'=>$unionpay_total_amount,
                'Bestpay_total_amount'=>$Bestpay_total_amount,
                'pos_total_amount'=>$pos_total_amount,
                'commission_money'=>$commission_money,
                'addstores'=>$addstores,
                'date'=>'所选日期'
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }
        
        }
    }
    
    public function commission_store(Request $request){
        $format = [];
        $curHdIndex = $request->get('curHdIndex', '');
        $inputValue=$request->get('inputValue', '');
        $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
        $date_start = $request->get('start_data', '');
        $date_end = $request->get('end_data', '');
        try{
            $total_amount='0.00';
            $refund_amount='0.00';
            $total_commission='0.00';
            $share_commission='0.00';
            $service_commission='0.00';
            $total_fee='0.00';
            $store_company=[];
            $login_user = User::where('id', $user_id)->where('is_delete', '=', '0')->first();
            if (!$login_user) {
                throw new \Exception("登录异常");
            }
            
            switch (intval($curHdIndex)) {
                case 1://今日
                    $date_start = date('Y-m-d 00:00:00');
                    $date_end = date('Y-m-d 23:59:59');
                    break;
                case 2://昨日
                    $date_start = date('Y-m-d 00:00:00', strtotime("-1 day"));
                    $date_end = date('Y-m-d 23:59:59', strtotime("-1 day"));
                    break;
                case 3://上周
                    $date_start = date('Y-m-d 00:00:00', strtotime('last week'));
                    $date_end = date('Y-m-d 23:59:59', strtotime('this week -1 day'));
                    break;
                case 4://本月
                    $date_start = date('Y-m-01 00:00:00');
                    $date_end = date('Y-m-t 23:59:59');
                    break;
                case 5://上月
                    $date_start = date('Y-m-01 00:00:00', strtotime('-1 month', time()));
                    $date_end = date('Y-m-t 23:59:59', strtotime('-1 month', time()));
                    break;
            }
            $time_end = strtotime($date_end);
            $time_start = strtotime($date_start);
            if ($time_end<$date_start){
                throw new \Exception("结束时间不能大于开始时间");
            }
            if ($time_start<strtotime('2023-06-01')){
                throw new \Exception("查询最小时间不能低于2023-06-01");
            }
            if ($time_end>strtotime(date('Y-m-t 23:59:59'))){
                throw new \Exception("查询最大时间不能高于当月");
            }
            $cache_key = 'agent:sub_list';
            $db = DB::connection();
            $agentSubList = Cache::get($cache_key,false);
            if ($agentSubList == false) {
                $agentSubList = [];
                $agentList = $db->table('users')->pluck('pid', 'id');
                foreach ($agentList as $_id => $pid) {
                    $agentSubList[$_id] = $this->getAgentSubId($_id, $agentList);
                }
                if (is_array($agentSubList) && count($agentSubList) > 0) {
                    Cache::add($cache_key, $agentSubList, 120);
                }
            }
            $user_rates = $db->table('user_rates')->where('user_id', $user_id)->pluck(DB::raw("CONCAT(server_rate,':',era_rate,':',rate,':',yu_rate)"), 'ways_type')->toArray();
            $monthTotal = $this->getMonthDifference(strtotime($date_start), strtotime($date_end));
            $agentIds = array_merge($agentSubList[$user_id], [$user_id]);
            $storeObj = $db->table('stores')->whereIn('user_id', $agentIds)->where(function ($query) use ($inputValue) {
                $query->where('pid', 0);
                if ($inputValue && $inputValue != 'undefined') {
                    $query->where('store_name', 'like', '%' . $inputValue . '%');
                }
                return $query;
            })->select([
                'store_id',
                'store_name',
                DB::raw('0.00 as commission_money'),
                DB::raw('0.00 as fee_amount'),
                DB::raw('0.00 as refund_amount'),
                DB::raw('0.00 as total_amount'),
                DB::raw('0 as total_num'),
            ])->orderBy('sort','desc');
            $this->t = $storeObj->count();
            $storeList = $this->page($storeObj)->get()->toArray();
            if (is_array($user_rates)) {
                $storeIds = array_column($storeList, 'store_id');
                $tableName = 'wft_stores_orders_' . date('Ym', strtotime($date_start)) . '_bill';
                $pluck = DB::connection('old_mysql')->table($tableName)
                    ->whereIn('sales_id', $agentIds)
                    ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                    ->select([
                        'store_id',
                        'receive_code',
                        'receive_rate',
                        'receive_model',
                        DB::raw('sum(receive_fee) as receive_fee'),
                        DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                        DB::raw('sum(order_total) as order_total'),
                        DB::raw('sum(order_amount) as order_amount'),
                        DB::raw('sum(refund_total) as refund_total'),
                        DB::raw('sum(refund_amount) as refund_amount'),
                    ])
                    ->groupBy(Db::raw('store_id,receive_code,receive_rate,receive_model'));
                for ($i = 0; $i < $monthTotal; $i++) {
                    $num = $i + 1;
                    $numTime = strtotime("+" . $num . " month", strtotime($date_start));
                    $tableName = 'wft_stores_orders_' . date('Ym', $numTime) . '_bill';
                    $union_pluck = DB::connection('old_mysql')->table($tableName)
                        ->whereIn('sales_id', $agentIds)
                        ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                        ->select([
                            'store_id',
                            'receive_code',
                            'receive_rate',
                            'receive_model',
                            DB::raw('sum(receive_fee) as receive_fee'),
                            DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                            DB::raw('sum(order_total) as order_total'),
                            DB::raw('sum(order_amount) as order_amount'),
                            DB::raw('sum(refund_total) as refund_total'),
                            DB::raw('sum(refund_amount) as refund_amount'),
                        ])
                        ->groupBy(Db::raw('store_id,receive_code,receive_rate,receive_model'));
                    $pluck->unionAll($union_pluck);
                }
                foreach ($pluck->get() as $obj) {
                    $item = (array)$obj;
                    $store_index = array_search($item['store_id'],$storeIds);
                    if (!isset($user_rates[$item['receive_code']])){
                        continue;
                    }
                    $company_rates = explode(':',$user_rates[$item['receive_code']]);
                    $user_rate = $company_rates[$item['receive_model'] - 1];
                    $_commission_money=0.00;
//                    if ($user_rate > 0 && $item['receive_rate'] > $user_rate) {
                        $_commission_money = bcmul(bcdiv(bcsub($item['receive_rate'], $user_rate, 2), 100, 4), bcsub($item['order_amount'], $item['refund_amount']), 2);
                        $_commission_money = bcdiv($_commission_money, 100, 2);
//                    }
                    $_fee_amount=bcdiv(bcmul(bcdiv($item['receive_rate'], 100, 4), bcsub($item['order_amount'], $item['refund_amount']), 2),100,2);
                    $_refund_amount=bcdiv($item['refund_amount'], 100, 2);
                    $_total_amount=bcdiv($item['order_amount'],100,2);
                    $_total_num=$item['order_total'];
                    if($store_index!==false){
                        $store_info= (array)$storeList[$store_index];
                        if(!isset($store_info['commission_money'])){
                            $store_info['commission_money']=0.00;
                        }
                        if(!isset($store_info['fee_amount'])){
                            $store_info['fee_amount']=0.00;
                        }
                        if(!isset($store_info['refund_amount'])){
                            $store_info['refund_amount']=0.00;
                        }
                        if(!isset($store_info['total_amount'])){
                            $store_info['total_amount']=0.00;
                        }
                        if(!isset($store_info['total_num'])){
                            $store_info['total_num']=0;
                        }
                        $store_info['commission_money']=bcadd($store_info['commission_money'],$_commission_money,2);
                        $store_info['fee_amount']=bcadd($store_info['fee_amount'],$_fee_amount,2);
                        $store_info['refund_amount']=bcadd($store_info['refund_amount'],$_refund_amount,2);
                        $store_info['total_amount']=bcadd($store_info['total_amount'],$_total_amount,2);
                        $store_info['total_num']=bcadd($store_info['total_num'],$_total_num);
                        $storeList[$store_index] = $store_info;
                    }
                    $total_amount=bcadd($total_amount, $_total_amount, 2);
                    $refund_amount=bcadd($refund_amount, $_refund_amount, 2);
                    $total_commission=bcadd($total_commission, $_commission_money, 2);
                    $total_fee=bcadd($total_fee,$_fee_amount,2);
                }

            }
            $this->status = '1';
            $this->message = '数据返回成功';
            $format=[
                'service_commission'=>$service_commission,
                'share_commission'=>$share_commission,
                'total_amount' => bcsub($total_amount, $refund_amount, 2),
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$storeList,
            ];
        }catch (\Exception $e){
            $this->status = 2;
            $this->message = $e->getMessage().$e->getFile().$e->getLine();
        }
        return $this->format($format);
    }

    //计算代理商分佣
    public function _commission_store(Request $request){
        $token = $this->parseToken();
        $token_user_id = $token->user_id;
        $curHdIndex=$request->get('curHdIndex', '');
        $inputValue=$request->get('inputValue', '');
        if($inputValue=='undefined'){
            $inputValue='';
        }
         error_log(date('Y-m-d H:i:s')." 【计算代理商分佣】： ".json_encode([$token_user_id, $curHdIndex, $inputValue])."\n\n", 3, "/www/wwwlogs/wft/". 'commission_store'.date('Ymd').".log");

        $login_user = User::where('id', $token_user_id)
            ->where('is_delete', '=', '0')
            ->first();
        if (!$login_user) {
            $this->status = '2';
            $this->message = '当前登录状态异常';
            return $this->format();
        }
        $user_ids = $this->getSubIds($token_user_id);
        if($token_user_id==347){
            $user_ids = $this->getSubIds(1);
            $pingan_stores=DB::table('pingan_stores')->where('type', 1)->select('store_id')->get();
            $store_ids4=[];
            foreach ($pingan_stores as $k=>$v){
                $store_ids4[$k]=$v->store_id;
            }
            if(!empty($inputValue)){
                $obj=DB::table('stores')->whereIn('store_id', $store_ids4)->where('store_name', 'like','%' . $inputValue . '%')->where('pid', '=',0)->select('store_id','store_name','id','rata_status')->orderBy('sort','desc');
            }else{
                $obj=DB::table('stores')->whereIn('store_id', $store_ids4)->where('pid', '=',0)->select('store_id','store_name','id','rata_status')->orderBy('sort','desc');
            }
        }else{
            if(!empty($inputValue)){
                $obj=DB::table('stores')->whereIn('user_id', $user_ids)->where('store_name', 'like','%' . $inputValue . '%')->where('pid', '=',0)->select('store_id','store_name','id','rata_status')->orderBy('sort','desc');
            }else{
                $obj=DB::table('stores')->whereIn('user_id', $user_ids)->where('pid', '=',0)->select('store_id','store_name','id','rata_status')->orderBy('sort','desc');
            }
        }
        $this->t = $obj->count();
        $store_ids = $this->page($obj)->get();

        $store_ids=json_decode($store_ids,true);
        if(empty($store_ids)){
            $return_data=array(
                'total_amount'=>0.00,
                'total_commission'=>0.00,
                'total_fee'=>0.00,
                'store_company'=>[],
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }
        foreach($store_ids as $k=>$v){
            $store_data[$k]=$v['store_id'];
        }
        $store_ids1=DB::table('stores')->whereIn('user_id', $user_ids)->select('store_id','store_name','id')->get();
        $store_ids1=json_decode($store_ids1,true);
        foreach($store_ids1 as $k=>$v){
            $store_data1[$k]=$v['store_id'];
        }
        $table1='wft_stores_orders_202307_bill';
        $table2='wft_stores_orders_202306_bill';
        if($token_user_id==347){
            if($curHdIndex ==1){
            $where[] = ['created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
            $where[] = ['created_at', '<=', date('Y-m-d', time()).' 23:59:59'];
            //总收款
            $total_amount=Order::whereIn('store_id', $store_ids4)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
            //总佣金
            $total_commission='未结算';
            $share_commission='未结算';
            $service_commission='未结算';
            $commission_fee=Order::whereIn('store_id', $store_ids4)->where($where)->whereIn('pay_status', [1, 6])->select('fee_amount')->sum('fee_amount');
            $server_fee=Order::whereIn('store_id', $store_ids4)->where($where)->whereIn('pay_status', [1, 6])->select('rata_money')->sum('rata_money');
            $total_fee=bcadd($commission_fee,$server_fee,2);
            foreach($store_ids as $key=>$val){
                $p_stores=DB::table('stores')->where('pid',$val['id'])->select('store_id')->get();
                if(!empty($p_stores[0]->store_id)){
                    $p_store_data[0]=$val['store_id'];
                    $p_stores=json_decode($p_stores,true);
                    foreach($p_stores as $k1=>$v1){
                        $p_store_data[]=$v1['store_id'];
                    }
                    $store_arr['store_name']=$val['store_name'];
                    $store_arr['store_id']=$val['store_id'];
                    $store_arr['total_amount']=Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
                    $store_arr['total_num']=Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->count('total_amount');
                    $store_arr['refund_amount']=Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('refund_amount')->sum('refund_amount');
                    $rata_money=Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('rata_money')->sum('rata_money');
                    $fee_amount=Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('fee_amount')->sum('fee_amount');
                    $store_arr['fee_amount']=bcadd($rata_money,$fee_amount,2);
                    $store_arr['commission_money']='未结算';

                    $store_arr_data[]=$store_arr;
                }else{
                    $store_arr['store_id']=$val['store_id'];
                    $store_arr['store_name']=$val['store_name'];
                    $store_arr['total_amount']=Order::where('store_id', $val['store_id'])->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
                    $store_arr['refund_amount']=Order::where('store_id', $val['store_id'])->where($where)->whereIn('pay_status', [1, 6])->select('refund_amount')->sum('refund_amount');
                    $store_arr['total_num']=Order::where('store_id', $val['store_id'])->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->count('total_amount');
                    $rata_money=Order::where('store_id', $val['store_id'])->where($where)->whereIn('pay_status', [1, 6])->select('rata_money')->sum('rata_money');
                    $fee_amount=Order::where('store_id', $val['store_id'])->where($where)->whereIn('pay_status', [1, 6])->select('fee_amount')->sum('fee_amount');
                    $store_arr['fee_amount']=bcadd($rata_money,$fee_amount,2);
                    $store_arr['commission_money']='未结算';
                    $store_arr_data[]=$store_arr;
                }
                unset($p_store_data);
//                $pay_way=DB::table('store_pay_ways')->where('store_id', $val['store_id'])->select('company')->distinct()->get();
//                foreach ($pay_way as $data=>$item){
//                    if($item->company=='vbill'){
//                        $store_arr['company']='随行付';
//                    }else if($item->company=='wftpay'){
//                        $store_arr['company']='徽商银行';
//                    }else if($item->company=='wingpay'){
//                        $store_arr['company']='翼支付';
//                    }else if($item->company=='pingan'){
//                        $store_arr['company']='平安银行';
//                    }
//                }
            }
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'share_commission'=>$share_commission,
                'service_commission'=>$service_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==2){
            $where[] = ['settling_day', '>=', date('Y-m-d',strtotime("-1 day"))];
            $where[] = ['settling_day', '<=', date('Y-m-d',strtotime("-1 day"))];
            //总收款
            $total_amount=DB::table('company_day_commission')->where('user_id', 1)->whereIn('store_id', $store_ids4)->where($where)->select('total_amount')->sum('total_amount');
            //总佣金
            $total_commission=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            //分润佣金
            $share_commission=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where('is_rate',0)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            //服务费佣金
            $service_commission=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where('is_rate',1)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            $total_fee=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where($where)->where('user_id',$token_user_id)->select('fee_amount')->sum('fee_amount');
            foreach($store_ids as $key=>$val){
                $p_stores=DB::table('stores')->where('pid',$val['id'])->select('store_id')->get();
                if(!empty($p_stores[0]->store_id)){
                    $p_store_data[0]=$val['store_id'];
                    $p_stores=json_decode($p_stores,true);
                    foreach($p_stores as $k1=>$v1){
                        $p_store_data[]=$v1['store_id'];
                    }
                    $store_arr['store_id']=$val['store_id'];
                    $store_arr['store_name']=$val['store_name'];
                    $store_arr['total_amount']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('store_amount')->sum('store_amount');
                    $store_arr['total_num']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('store_order_count')->sum('store_order_count');
                    $store_arr['fee_amount']=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where)->where('user_id',$token_user_id)->select('fee_amount')->sum('fee_amount');
                    $store_arr['commission_money']=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
                    $store_arr['refund_amount']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('refund_amount')->sum('refund_amount');
                    $store_arr_data[]=$store_arr;
                }else{
                    $store_arr['store_id']=$val['store_id'];
                    $store_arr['store_name']=$val['store_name'];
                    $store_arr['total_amount']=DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('store_amount')->sum('store_amount');
                    $store_arr['total_num']=DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('store_order_count')->sum('store_order_count');
                    $store_arr['fee_amount']=DB::table('company_day_commission')->where('store_id', $val['store_id'])->where($where)->where('user_id',$token_user_id)->select('fee_amount')->sum('fee_amount');
                    $store_arr['commission_money']=DB::table('company_day_commission')->where('store_id', $val['store_id'])->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
                    $store_arr['refund_amount']=DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('commission_money')->sum('refund_amount');
                    $store_arr_data[]=$store_arr;
                }
                unset($p_store_data);
            }
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'share_commission'=>$share_commission,
                'service_commission'=>$service_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==3){
            $where[] = ['settling_day', '>=', date('Y-m-d', strtotime('last week'))];
            $where[] = ['settling_day', '<=', date('Y-m-d', strtotime('this week -1 day'))];
            //总收款
            $total_amount=DB::table('company_day_commission')->where('user_id', 1)->whereIn('store_id', $store_ids4)->where($where)->select('total_amount')->sum('total_amount');
            //总佣金
            $total_commission=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            //分润佣金
            $share_commission=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where('is_rate',0)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            //服务费佣金
            $service_commission=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where('is_rate',1)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            $total_fee=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where($where)->where('user_id',$token_user_id)->select('fee_amount')->sum('fee_amount');
            foreach($store_ids as $key=>$val){
                $p_stores=DB::table('stores')->where('pid',$val['id'])->select('store_id')->get();
                if(!empty($p_stores[0]->store_id)){
                    $p_store_data[0]=$val['store_id'];
                    $p_stores=json_decode($p_stores,true);
                    foreach($p_stores as $k1=>$v1){
                        $p_store_data[]=$v1['store_id'];
                    }
                    $store_arr['store_id']=$val['store_id'];
                    $store_arr['store_name']=$val['store_name'];
                    $store_arr['total_amount']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('store_amount')->sum('store_amount');
                    $store_arr['total_num']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('store_order_count')->sum('store_order_count');
                    $store_arr['fee_amount']=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where)->where('user_id',$token_user_id)->select('fee_amount')->sum('fee_amount');
                    $store_arr['commission_money']=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
                    $store_arr['refund_amount']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('refund_amount')->sum('refund_amount');
                    $store_arr_data[]=$store_arr;
                }else{
                    $store_arr['store_id']=$val['store_id'];
                    $store_arr['store_name']=$val['store_name'];
                    $store_arr['total_amount']=DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('store_amount')->sum('store_amount');
                    $store_arr['total_num']=DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('store_order_count')->sum('store_order_count');
                    $store_arr['fee_amount']=DB::table('company_day_commission')->where('store_id', $val['store_id'])->where($where)->where('user_id',$token_user_id)->select('fee_amount')->sum('fee_amount');
                    $store_arr['commission_money']=DB::table('company_day_commission')->where('store_id', $val['store_id'])->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
                    $store_arr['refund_amount']=DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('commission_money')->sum('refund_amount');
                    $store_arr_data[]=$store_arr;
                }
                unset($p_store_data);
            }
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'share_commission'=>$share_commission,
                'service_commission'=>$service_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==4){
            $where[] = ['settling_day', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
            $where[] = ['settling_day', '<=', date('Y-m-d', strtotime("-1 day"))];
            // dump($where);die;
            //总收款
            $total_amount=DB::table('company_day_commission')->where('user_id', 1)->whereIn('store_id', $store_ids4)->where($where)->select('total_amount')->sum('total_amount');
            //总佣金
            $total_commission=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            //分润佣金
            $share_commission=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where('is_rate',0)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            //服务费佣金
            $service_commission=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where('is_rate',1)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            $total_fee=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where($where)->where('user_id',$token_user_id)->select('fee_amount')->sum('fee_amount');
            foreach($store_ids as $key=>$val){
                $p_stores=DB::table('stores')->where('pid',$val['id'])->select('store_id')->get();
                if(!empty($p_stores[0]->store_id)){
                    $p_store_data[0]=$val['store_id'];
                    $p_stores=json_decode($p_stores,true);
                    foreach($p_stores as $k1=>$v1){
                        $p_store_data[]=$v1['store_id'];
                    }
                    $store_arr['store_id']=$val['store_id'];
                    $store_arr['store_name']=$val['store_name'];
                    $store_arr['total_amount']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('store_amount')->sum('store_amount');
                    $store_arr['total_num']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('store_order_count')->sum('store_order_count');
                    $store_arr['fee_amount']=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where)->where('user_id',$token_user_id)->select('fee_amount')->sum('fee_amount');
                    $store_arr['commission_money']=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
                    $store_arr['refund_amount']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('refund_amount')->sum('refund_amount');
                    $store_arr_data[]=$store_arr;
                }else{
                    $store_arr['store_id']=$val['store_id'];
                    $store_arr['store_name']=$val['store_name'];
                    $store_arr['total_amount']=DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('store_amount')->sum('store_amount');
                    $store_arr['total_num']=DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('store_order_count')->sum('store_order_count');
                    $store_arr['fee_amount']=DB::table('company_day_commission')->where('store_id', $val['store_id'])->where($where)->where('user_id',$token_user_id)->select('fee_amount')->sum('fee_amount');
                    $store_arr['commission_money']=DB::table('company_day_commission')->where('store_id', $val['store_id'])->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
                    $store_arr['refund_amount']=DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('commission_money')->sum('refund_amount');
                    $store_arr_data[]=$store_arr;
                }
                unset($p_store_data);
            }
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'share_commission'=>$share_commission,
                'service_commission'=>$service_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==5){
            $where[] = ['settling_day', '>=', date('Y-m-01', strtotime(date('Y-m-01') . " - 1 month"))];
            $where[] = ['settling_day', '<=', date('Y-m-t', strtotime('-1 month'))];
            //总收款
            $total_amount=DB::table('company_day_commission')->where('user_id', 1)->whereIn('store_id', $store_ids4)->where($where)->select('total_amount')->sum('total_amount');
            //总佣金
            $total_commission=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where($where)->where('user_id', $token_user_id)->select('commission_money')->sum('commission_money');
            // dump($token_user_id);die;
            //分润佣金
            $share_commission=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where('is_rate',0)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            //服务费佣金
            $service_commission=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where('is_rate',1)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            $total_fee=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where($where)->where('user_id',$token_user_id)->select('fee_amount')->sum('fee_amount');
            foreach($store_ids as $key=>$val){
                $p_stores=DB::table('stores')->where('pid',$val['id'])->select('store_id')->get();
                if(!empty($p_stores[0]->store_id)){
                    $p_store_data[0]=$val['store_id'];
                    $p_stores=json_decode($p_stores,true);
                    foreach($p_stores as $k1=>$v1){
                        $p_store_data[]=$v1['store_id'];
                    }
                    $store_arr['store_id']=$val['store_id'];
                    $store_arr['store_name']=$val['store_name'];
                    $store_arr['total_amount']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('store_amount')->sum('store_amount');
                    $store_arr['total_num']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('store_order_count')->sum('store_order_count');
                    $store_arr['fee_amount']=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where)->where('user_id',$token_user_id)->select('fee_amount')->sum('fee_amount');
                    $store_arr['commission_money']=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
                    $store_arr['refund_amount']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('refund_amount')->sum('refund_amount');
                    $store_arr_data[]=$store_arr;
                }else{
                    $store_arr['store_id']=$val['store_id'];
                    $store_arr['store_name']=$val['store_name'];
                    $store_arr['total_amount']=DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('store_amount')->sum('store_amount');
                    $store_arr['total_num']=DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('store_order_count')->sum('store_order_count');
                    $store_arr['fee_amount']=DB::table('company_day_commission')->where('store_id', $val['store_id'])->where($where)->where('user_id',$token_user_id)->select('fee_amount')->sum('fee_amount');
                    $store_arr['commission_money']=DB::table('company_day_commission')->where('store_id', $val['store_id'])->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
                    $store_arr['refund_amount']=DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('commission_money')->sum('refund_amount');
                    $store_arr_data[]=$store_arr;
                }
                unset($p_store_data);
            }
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'share_commission'=>$share_commission,
                'service_commission'=>$service_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex == 6){
            $start_data = $request->get('start_data', '');
            $end_data = $request->get('end_data', '');
            $where[] = ['settling_day', '>=', $start_data];
            $where[] = ['settling_day', '<=', $end_data];
            
            if ($start_data != $end_data) {
                $date = ((strtotime($end_data) > strtotime($start_data))) ? true : false;
                if (!$date) {
                    $this->status = '2';
                    $this->message = '开始时间不能超过结束时间';
                    return $this->format(2);
                }
            }
            
            // //限制时间
            $date = (strtotime($end_data) - strtotime($start_data)) / 86400;
            $day = 31;
            if ($date > $day) {
                $this->status = '2';
                $this->message = "时间筛选不能超过 $day 天";
                return $this->format(2);
            }
            // print_r($where);die;
            
            // $now = time();
            // $time = strtotime('-2 month', $now);
            // $beginTime = date('Y-m-d', mktime(0, 0, 0, date('m', $time), 1, date('Y', $time)));
            
            // // dump( strtotime($start_data) );die; // 2022-01-01 00:00:00
            // if( strtotime($start_data) - $time < 0 ){
            //     $this->status = '2';
            //     $this->message = "仅支持查询最近三个月的订单";
            //     return $this->format(2);
            // }
            
            //总收款
            $total_amount=DB::table('company_day_commission')->where('user_id', 1)->whereIn('store_id', $store_ids4)->where($where)->select('total_amount')->sum('total_amount');
            //总佣金
            $total_commission=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            //分润佣金
            $share_commission=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where('is_rate',0)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            //服务费佣金
            $service_commission=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where('is_rate',1)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            $total_fee=DB::table('company_day_commission')->whereIn('store_id', $store_ids4)->where($where)->where('user_id',$token_user_id)->select('fee_amount')->sum('fee_amount');
            foreach($store_ids as $key=>$val){
                $p_stores=DB::table('stores')->where('pid',$val['id'])->select('store_id')->get();
                if(!empty($p_stores[0]->store_id)){
                    $p_store_data[0]=$val['store_id'];
                    $p_stores=json_decode($p_stores,true);
                    foreach($p_stores as $k1=>$v1){
                        $p_store_data[]=$v1['store_id'];
                    }
                    $store_arr['store_id']=$val['store_id'];
                    $store_arr['store_name']=$val['store_name'];
                    $store_arr['total_amount']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('store_amount')->sum('store_amount');
                    $store_arr['total_num']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('store_order_count')->sum('store_order_count');
                    $store_arr['fee_amount']=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where)->where('user_id',$token_user_id)->select('fee_amount')->sum('fee_amount');
                    $store_arr['commission_money']=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
                    $store_arr['refund_amount']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('refund_amount')->sum('refund_amount');
                    $store_arr_data[]=$store_arr;
                }else{
                    $store_arr['store_id']=$val['store_id'];
                    $store_arr['store_name']=$val['store_name'];
                    $store_arr['total_amount']=DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('store_amount')->sum('store_amount');
                    $store_arr['total_num']=DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('store_order_count')->sum('store_order_count');
                    $store_arr['fee_amount']=DB::table('company_day_commission')->where('store_id', $val['store_id'])->where($where)->where('user_id',$token_user_id)->select('fee_amount')->sum('fee_amount');
                    $store_arr['commission_money']=DB::table('company_day_commission')->where('store_id', $val['store_id'])->where($where)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
                    $store_arr['refund_amount']=DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('commission_money')->sum('refund_amount');
                    $store_arr_data[]=$store_arr;
                }
                unset($p_store_data);
            }
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'share_commission'=>$share_commission,
                'service_commission'=>$service_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }
        }else{
            if($curHdIndex ==1){
            $where[] = ['created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
            $where[] = ['created_at', '<=', date('Y-m-d', time()).' 23:59:59'];
            //总收款
            $total_amount=DB::table('orders')->whereIn('user_id', $user_ids)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
            //总佣金
            $total_commission='未结算';
            $share_commission='未结算';
            $service_commission='未结算';
            $commission_fee=DB::table('orders')->whereIn('user_id', $user_ids)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount');

            $server_fee=0.00;
            $total_fee=bcadd($commission_fee,$server_fee,2);
            foreach($store_ids as $key=>$val){
                unset($where);
                $where[] = ['orders.created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
                $where[] = ['orders.created_at', '<=', date('Y-m-d', time()).' 23:59:59'];
                $store_arr['store_name']=$val['store_name'];
                $store_arr['store_id']=$val['store_id'];
                $id=$val['id'];
                $result = DB::table('orders')->join('stores', function ($join) {
                    $join->on('orders.store_id', '=', 'stores.store_id');
                })
                    ->whereIn('orders.pay_status', [1, 6])
                    ->where($where)
                    ->where(function ($query) use($id) {
                        $query->where('stores.id', $id)->orwhere('stores.pid', $id);
                        return $query;
                    })
                    ->select([DB::raw('sum(orders.fee_amount) as fee_amount'),DB::raw('sum(orders.rata_money) as rata_money'),DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total'),DB::raw('sum(orders.refund_amount) as refund_amount')])
                    ->first();
                $store_arr['total_amount']=$result->total_amount?$result->total_amount:0.00;
                $store_arr['total_num']=$result->total;
                $store_arr['refund_amount']=$result->refund_amount?$result->refund_amount:0.00;
                $rata_money=$result->rata_money;;
                $fee_amount=$result->fee_amount;;

                $store_arr['fee_amount']=bcadd($rata_money,$fee_amount,2);
                $store_arr['commission_money']='未结算';

                $store_arr_data[]=$store_arr;
            }
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'share_commission'=>$share_commission,
                'service_commission'=>$service_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==2){
            $where[] = ['bill_date', '>=', strtotime('yesterday')];
            $where[] = ['bill_date', '<=', strtotime('yesterday')+86399];
            $where_c[] = ['settling_day', '>=', date('Y-m-d',strtotime("-1 day"))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d',strtotime("-1 day"))];
            $start_date=date('Y-m-d',strtotime("-1 day"));
            $end_date=date('Y-m-d',strtotime("-1 day"));
               //总收款
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $total_amount += $obj->order_amount;
                }
                $total_amount=$total_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=bcsub($total_amount,$refund_amount,2);
            //总佣金
            $start_commission=date('Y-m-d',strtotime("-1 day"));
            $end_commission=date('Y-m-d',strtotime("-1 day"));
            $get_commission=$start_commission.','.$end_commission;
            $total_commission=DB::table('company_day_commission')->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            //分润佣金
            $share_commission=0.00;
            //服务费佣金
            $service_commission=0.00;
            $total_fee=$refund_amount;

            foreach($store_ids as $key=>$val){
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $ways_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $ways_amount_zong += $obj->order_amount;
                    }
                    $ways_amount_zong=$ways_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $refund_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $refund_amount_zong += $obj->refund_amount;
                    }
                    $refund_amount_zong=$refund_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount->unionAll($ways_amount1);
                    $order_total_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $order_total_zong += $obj->order_total;
                    }
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $ways_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('refund_amount')->sum('refund_amount')/100;
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_total')->sum('order_total');
                    
                }
                $total_amount_s=$ways_amount_zong;
                
                $total_num=$order_total_zong;
                
                $fee_amount='0.00';
                
                $commission_money='0.00';
                $refund_amount=$refund_amount_zong;
                $store_arr['store_id']=$val['store_id'];
                $store_arr['store_name']=$val['store_name'];
                $store_arr['total_amount']=$total_amount_s;
                $store_arr['total_num']=$total_num;
                $store_arr['fee_amount']=$fee_amount;
                $store_arr['commission_money']=$commission_money;
                $store_arr['refund_amount']=$refund_amount;
                $store_arr_data[]=$store_arr;
            }
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'share_commission'=>$share_commission,
                'service_commission'=>$service_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
            );
            
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==3){
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'))];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime('last week'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime('this week -1 day'))];
            $start_date=date('Y-m-d', strtotime('last week'));
            $end_date=date('Y-m-d', strtotime('this week -1 day'));
              //总收款
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $total_amount += $obj->order_amount;
                }
                $total_amount=$total_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=bcsub($total_amount,$refund_amount,2);
            //总佣金
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            $total_commission=DB::table('company_day_commission')->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            //分润佣金
            $share_commission=0.00;
            //服务费佣金
            $service_commission=0.00;
            $total_fee=$refund_amount;

            foreach($store_ids as $key=>$val){
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $ways_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $ways_amount_zong += $obj->order_amount;
                    }
                    $ways_amount_zong=$ways_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $refund_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $refund_amount_zong += $obj->refund_amount;
                    }
                    $refund_amount_zong=$refund_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount->unionAll($ways_amount1);
                    $order_total_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $order_total_zong += $obj->order_total;
                    }
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $ways_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('refund_amount')->sum('refund_amount')/100;
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_total')->sum('order_total');
                    
                }
                $total_amount_s=$ways_amount_zong;
                
                $total_num=$order_total_zong;
                
                $fee_amount='0.00';
                
                $commission_money='0.00';
                $refund_amount=$refund_amount_zong;
                $store_arr['store_id']=$val['store_id'];
                $store_arr['store_name']=$val['store_name'];
                $store_arr['total_amount']=$total_amount_s;
                $store_arr['total_num']=$total_num;
                $store_arr['fee_amount']=$fee_amount;
                $store_arr['commission_money']=$commission_money;
                $store_arr['refund_amount']=$refund_amount;
                $store_arr_data[]=$store_arr;
            }
                $return_data=array(
                    'total_amount'=>$total_amount,
                    'total_commission'=>$total_commission,
                    'share_commission'=>$share_commission,
                    'service_commission'=>$service_commission,
                    'total_fee'=>$total_fee,
                    'store_company'=>$store_arr_data,
                );
                $this->status = '1';
                $this->message = '数据返回成功';
                return $this->format($return_data);
        }else if($curHdIndex ==4){
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),1,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(0,0,0,date('m'),date('d'),date('Y'))-1];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime("-1 day"))];
            $start_date=date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'));
            $end_date=date('Y-m-d',strtotime("-1 day"));
            // dump($where);die;
                //总收款
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $total_amount += $obj->order_amount;
                }
                $total_amount=$total_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=bcsub($total_amount,$refund_amount,2);
            //总佣金
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            $total_commission=DB::table('company_day_commission')->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            //分润佣金
            $share_commission=0.00;
            //服务费佣金
            $service_commission=0.00;
            $total_fee=$refund_amount;

            foreach($store_ids as $key=>$val){
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $ways_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $ways_amount_zong += $obj->order_amount;
                    }
                    $ways_amount_zong=$ways_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $refund_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $refund_amount_zong += $obj->refund_amount;
                    }
                    $refund_amount_zong=$refund_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount->unionAll($ways_amount1);
                    $order_total_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $order_total_zong += $obj->order_total;
                    }
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $ways_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('refund_amount')->sum('refund_amount')/100;
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_total')->sum('order_total');
                    
                }
                $total_amount_s=$ways_amount_zong;
                
                $total_num=$order_total_zong;
                
                $fee_amount='0.00';
                
                $commission_money='0.00';
                $refund_amount=$refund_amount_zong;
                $store_arr['store_id']=$val['store_id'];
                $store_arr['store_name']=$val['store_name'];
                $store_arr['total_amount']=$total_amount_s;
                $store_arr['total_num']=$total_num;
                $store_arr['fee_amount']=$fee_amount;
                $store_arr['commission_money']=$commission_money;
                $store_arr['refund_amount']=$refund_amount;
                $store_arr_data[]=$store_arr;
            }
                $return_data=array(
                    'total_amount'=>$total_amount,
                    'total_commission'=>$total_commission,
                    'share_commission'=>$share_commission,
                    'service_commission'=>$service_commission,
                    'total_fee'=>$total_fee,
                    'store_company'=>$store_arr_data,
                );
                $this->status = '1';
                $this->message = '数据返回成功';
                return $this->format($return_data);
        }else if($curHdIndex ==5){
            $where[] = ['bill_date', '>=', strtotime(date('Y-m-01 00:00:00',strtotime(date('Y-m-01') . " - 1 month")))];
            $where[] = ['bill_date', '<=', strtotime(date("Y-m-d 23:59:59", strtotime(-date('d').'day')))];
            $where_c[] = ['settling_day', '>=', date('Y-m-01', strtotime('-1 month'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-t', strtotime('-1 month'))];
            $start_date=date('Y-m-01', strtotime(date('Y-m-01') . " - 1 month"));
            $end_date=date("Y-m-d", strtotime(-date('d').'day'));
                   //总收款
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $total_amount += $obj->order_amount;
                }
                $total_amount=$total_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=bcsub($total_amount,$refund_amount,2);
            //总佣金
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            $total_commission=DB::table('company_day_commission')->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');;
            //分润佣金
            $share_commission=0.00;
            //服务费佣金
            $service_commission=0.00;
            $total_fee=$refund_amount;

            foreach($store_ids as $key=>$val){
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $ways_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $ways_amount_zong += $obj->order_amount;
                    }
                    $ways_amount_zong=$ways_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $refund_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $refund_amount_zong += $obj->refund_amount;
                    }
                    $refund_amount_zong=$refund_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount->unionAll($ways_amount1);
                    $order_total_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $order_total_zong += $obj->order_total;
                    }
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $ways_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('refund_amount')->sum('refund_amount')/100;
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_total')->sum('order_total');
                    
                }
                $total_amount_s=$ways_amount_zong;
                
                $total_num=$order_total_zong;
                
                $fee_amount='0.00';
                
                $commission_money='0.00';
                $refund_amount=$refund_amount_zong;
                $store_arr['store_id']=$val['store_id'];
                $store_arr['store_name']=$val['store_name'];
                $store_arr['total_amount']=$total_amount_s;
                $store_arr['total_num']=$total_num;
                $store_arr['fee_amount']=$fee_amount;
                $store_arr['commission_money']=$commission_money;
                $store_arr['refund_amount']=$refund_amount;
                $store_arr_data[]=$store_arr;
            }
                $return_data=array(
                    'total_amount'=>$total_amount,
                    'total_commission'=>$total_commission,
                    'share_commission'=>$share_commission,
                    'service_commission'=>$service_commission,
                    'total_fee'=>$total_fee,
                    'store_company'=>$store_arr_data,
                );
                $this->status = '1';
                $this->message = '数据返回成功';
                return $this->format($return_data);
        }else if($curHdIndex == 6){
            $start_data = $request->get('start_data', '');
            $end_data = $request->get('end_data', '');
            $start_date=$start_data;
            $end_date=$end_data;
            $where[] = ['bill_date', '>=', strtotime($start_data.' 00:00:00')];
            $where[] = ['bill_date', '<=', strtotime($end_data.' 23:59:59')];
            $where_c[] = ['settling_day', '>=', $start_data];
            $where_c[] = ['settling_day', '<=', $end_data];
            
            if ($start_data != $end_data) {
                $date = ((strtotime($end_data) > strtotime($start_data))) ? true : false;
                if (!$date) {
                    $this->status = '2';
                    $this->message = '开始时间不能超过结束时间';
                    return $this->format(2);
                }
            }
            
            // //限制时间
            $date = (strtotime($end_data) - strtotime($start_data)) / 86400;
            $day = 31;
            if ($date > $day) {
                $this->status = '2';
                $this->message = "时间筛选不能超过 $day 天";
                return $this->format(2);
            }
                //总收款
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $total_amount += $obj->order_amount;
                }
                $total_amount=$total_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=bcsub($total_amount,$refund_amount,2);
            //总佣金
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            $total_commission=DB::table('company_day_commission')->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');;
            //分润佣金
            $share_commission=0.00;
            //服务费佣金
            $service_commission=0.00;
            $total_fee=$refund_amount;

            foreach($store_ids as $key=>$val){
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $ways_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $ways_amount_zong += $obj->order_amount;
                    }
                    $ways_amount_zong=$ways_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $refund_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $refund_amount_zong += $obj->refund_amount;
                    }
                    $refund_amount_zong=$refund_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount->unionAll($ways_amount1);
                    $order_total_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $order_total_zong += $obj->order_total;
                    }
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $ways_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('refund_amount')->sum('refund_amount')/100;
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_total')->sum('order_total');
                    
                }
                $total_amount_s=$ways_amount_zong;
                
                $total_num=$order_total_zong;
                
                $fee_amount='0.00';
                
                $commission_money='0.00';
                $refund_amount=$refund_amount_zong;
                $store_arr['store_id']=$val['store_id'];
                $store_arr['store_name']=$val['store_name'];
                $store_arr['total_amount']=$total_amount_s;
                $store_arr['total_num']=$total_num;
                $store_arr['fee_amount']=$fee_amount;
                $store_arr['commission_money']=$commission_money;
                $store_arr['refund_amount']=$refund_amount;
                $store_arr_data[]=$store_arr;
            }
                $return_data=array(
                    'total_amount'=>$total_amount,
                    'total_commission'=>$total_commission,
                    'share_commission'=>$share_commission,
                    'service_commission'=>$service_commission,
                    'total_fee'=>$total_fee,
                    'store_company'=>$store_arr_data,
                );
                $this->status = '1';
                $this->message = '数据返回成功';
                return $this->format($return_data);
        }
        }
    }
    
    public function sub_commission_store(Request $request){
        $format = [];
        $curHdIndex = $request->get('curHdIndex', '');
        $inputValue=$request->get('inputValue', '');
        $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
        $date_start = $request->get('start_data', date('Y-m-d 00:00:00'));
        $date_end = $request->get('end_data', date('Y-m-d 23:59:59'));
        try{
            $total_amount='0.00';
            $refund_amount='0.00';
            $total_commission='0.00';
            $share_commission='0.00';
            $service_commission='0.00';
            $total_fee='0.00';
            $store_company=[];
            $login_user = User::where('id', $user_id)->where('is_delete', '=', '0')->first();
            if (!$login_user) {
                throw new \Exception("登录异常");
            }
            $user_id = $request['user_id'];
            switch (intval($curHdIndex)) {
                case 1://今日
                    $date_start = date('Y-m-d 00:00:00');
                    $date_end = date('Y-m-d 23:59:59');
                    break;
                case 2://昨日
                    $date_start = date('Y-m-d 00:00:00', strtotime("-1 day"));
                    $date_end = date('Y-m-d 23:59:59', strtotime("-1 day"));
                    break;
                case 3://上周
                    $date_start = date('Y-m-d 00:00:00', strtotime('last week'));
                    $date_end = date('Y-m-d 23:59:59', strtotime('this week -1 day'));
                    break;
                case 4://本月
                    $date_start = date('Y-m-01 00:00:00');
                    $date_end = date('Y-m-t 23:59:59');
                    break;
                case 5://上月
                    $date_start = date('Y-m-01 00:00:00', strtotime('-1 month', time()));
                    $date_end = date('Y-m-t 23:59:59', strtotime('-1 month', time()));
                    break;
            }
            $time_end = strtotime($date_end);
            $time_start = strtotime($date_start);
            if ($time_end<$date_start){
                throw new \Exception("结束时间不能大于开始时间");
            }
            if ($time_start<strtotime('2023-06-01')){
                throw new \Exception("查询最小时间不能低于2023-06-01");
            }
            if ($time_end>strtotime(date('Y-m-t 23:59:59'))){
                throw new \Exception("查询最大时间不能高于当月");
            }
            $cache_key = 'agent:sub_list';
            $db = DB::connection();
            $agentSubList = Cache::get($cache_key,false);
            if ($agentSubList == false) {
                $agentSubList = [];
                $agentList = $db->table('users')->pluck('pid', 'id');
                foreach ($agentList as $_id => $pid) {
                    $agentSubList[$_id] = $this->getAgentSubId($_id, $agentList);
                }
                if (is_array($agentSubList) && count($agentSubList) > 0) {
                    Cache::add($cache_key, $agentSubList, 120);
                }
            }
            $user_rates = $db->table('user_rates')->where('user_id', $user_id)->pluck(DB::raw("CONCAT(server_rate,':',era_rate,':',rate,':',yu_rate)"), 'ways_type')->toArray();
            $monthTotal = $this->getMonthDifference(strtotime($date_start), strtotime($date_end));
            $agentIds = array_merge($agentSubList[$user_id], [$user_id]);
            $storeObj = $db->table('stores')->whereIn('user_id', $agentIds)->where(function ($query) use ($inputValue) {
                $query->where('pid', 0);
                if (!$inputValue && $inputValue != 'undefined') {
                    $query->where('store_name', 'like', '%' . $inputValue . '%');
                }
                return $query;
            })->select([
                'store_id',
                'store_name',
                DB::raw('0.00 as commission_money'),
                DB::raw('0.00 as fee_amount'),
                DB::raw('0.00 as refund_amount'),
                DB::raw('0.00 as total_amount'),
                DB::raw('0 as total_num'),
            ])->orderBy('sort','desc');
            $this->t = $storeObj->count();
            $storeList = $this->page($storeObj)->get()->toArray();
            if (is_array($user_rates)) {
                $storeIds = array_column($storeList, 'store_id');
                $tableName = 'wft_stores_orders_' . date('Ym', strtotime($date_start)) . '_bill';
                $pluck = DB::connection('old_mysql')->table($tableName)
                    ->whereIn('sales_id', $agentIds)
                    ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                    ->select([
                        'store_id',
                        'receive_code',
                        'receive_rate',
                        'receive_model',
                        DB::raw('sum(receive_fee) as receive_fee'),
                        DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                        DB::raw('sum(order_total) as order_total'),
                        DB::raw('sum(order_amount) as order_amount'),
                        DB::raw('sum(refund_total) as refund_total'),
                        DB::raw('sum(refund_amount) as refund_amount'),
                    ])
                    ->groupBy(Db::raw('store_id,receive_code,receive_rate,receive_model'));
                for ($i = 0; $i < $monthTotal; $i++) {
                    $num = $i + 1;
                    $numTime = strtotime("+" . $num . " month", strtotime($date_start));
                    $tableName = 'wft_stores_orders_' . date('Ym', $numTime) . '_bill';
                    $union_pluck = DB::connection('old_mysql')->table($tableName)
                        ->whereIn('sales_id', $agentIds)
                        ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                        ->select([
                            'store_id',
                            'receive_code',
                            'receive_rate',
                            'receive_model',
                            DB::raw('sum(receive_fee) as receive_fee'),
                            DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                            DB::raw('sum(order_total) as order_total'),
                            DB::raw('sum(order_amount) as order_amount'),
                            DB::raw('sum(refund_total) as refund_total'),
                            DB::raw('sum(refund_amount) as refund_amount'),
                        ])
                        ->groupBy(Db::raw('store_id,receive_code,receive_rate,receive_model'));
                    $pluck->unionAll($union_pluck);
                }
                foreach ($pluck->get() as $obj) {
                    $item = (array)$obj;
                    $store_index = array_search($item['store_id'],$storeIds);
                    if (!isset($user_rates[$item['receive_code']])){
                        continue;
                    }
                    $company_rates = explode(':',$user_rates[$item['receive_code']]);
                    $user_rate = $company_rates[$item['receive_model'] - 1];
                    $_commission_money=0.00;
//                    if ($user_rate > 0 && $item['receive_rate'] > $user_rate) {
                        $_commission_money = bcmul(bcdiv(bcsub($item['receive_rate'], $user_rate, 2), 100, 4), bcsub($item['order_amount'], $item['refund_amount']), 2);
                        $_commission_money = bcdiv($_commission_money, 100, 2);
//                    }
                    $_fee_amount=bcdiv(bcmul(bcdiv($item['receive_rate'], 100, 4), bcsub($item['order_amount'], $item['refund_amount']), 2),100,2);
                    $_refund_amount=bcdiv($item['refund_amount'], 100, 2);
                    $_total_amount=bcdiv($item['order_amount'],100,2);
                    $_total_num=$item['order_total'];
                    if($store_index!==false){
                        $store_info= (array)$storeList[$store_index];
                        if(!isset($store_info['commission_money'])){
                            $store_info['commission_money']=0.00;
                        }
                        if(!isset($store_info['fee_amount'])){
                            $store_info['fee_amount']=0.00;
                        }
                        if(!isset($store_info['refund_amount'])){
                            $store_info['refund_amount']=0.00;
                        }
                        if(!isset($store_info['total_amount'])){
                            $store_info['total_amount']=0.00;
                        }
                        if(!isset($store_info['total_num'])){
                            $store_info['total_num']=0;
                        }
                        $store_info['commission_money']=bcadd($store_info['commission_money'],$_commission_money,2);
                        $store_info['fee_amount']=bcadd($store_info['fee_amount'],$_fee_amount,2);
                        $store_info['refund_amount']=bcadd($store_info['refund_amount'],$_refund_amount,2);
                        $store_info['total_amount']=bcadd($store_info['total_amount'],$_total_amount,2);
                        $store_info['total_num']=bcadd($store_info['total_num'],$_total_num);
                        $storeList[$store_index] = $store_info;
                    }
                    $total_amount=bcadd($total_amount, $_total_amount, 2);
                    $refund_amount=bcadd($refund_amount, $_refund_amount, 2);
                    $total_commission=bcadd($total_commission, $_commission_money, 2);
                    $total_fee=bcadd($total_fee,$_fee_amount,2);
                }

            }
            $this->status = '1';
            $this->message = '数据返回成功';
            $format=[
                'service_commission'=>$service_commission,
                'share_commission'=>$share_commission,
                'total_amount'=>bcsub($total_amount,$refund_amount),
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$storeList,
            ];
        }catch (\Exception $e){
            $this->status = 2;
            $this->message = $e->getMessage();
        }
        return $this->format($format);
    }
    
    //计算下级代理商分佣
    public function _sub_commission_store(Request $request){
        $token = $this->parseToken();
        $token_user_id = $request['user_id'];
        $curHdIndex=$request->get('curHdIndex', '');
        $inputValue=$request->get('inputValue', '');
        if($inputValue=='undefined'){
            $inputValue='';
        }
         error_log(date('Y-m-d H:i:s')." 【计算代理商分佣1】： ".json_encode([$token_user_id, $curHdIndex, $inputValue])."\n\n", 3, "/www/wwwlogs/wft/". 'commission_store'.date('Ymd').".log");

        $login_user = User::where('id', $token_user_id)
            ->where('is_delete', '=', '0')
            ->first();
        if (!$login_user) {
            $this->status = '2';
            $this->message = '当前登录状态异常';
            return $this->format();
        }
        $user_ids = $this->getSubIds($token_user_id);
        if(!empty($inputValue)){
            $obj=DB::table('stores')->whereIn('user_id', $user_ids)->where('store_name', 'like','%' . $inputValue . '%')->where('pid', '=',0)->select('store_id','store_name','id','rata_status')->orderBy('sort','desc');
        }else{
            $obj=DB::table('stores')->whereIn('user_id', $user_ids)->where('pid', '=',0)->select('store_id','store_name','id','rata_status')->orderBy('sort','desc');
        }
        $this->t = $obj->count();
        $store_ids = $this->page($obj)->get();

        $store_ids=json_decode($store_ids,true);
        if(empty($store_ids)){
            $return_data=array(
                'total_amount'=>0.00,
                'total_commission'=>0.00,
                'total_fee'=>0.00,
                'store_company'=>[],
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }
        foreach($store_ids as $k=>$v){
            $store_data[$k]=$v['store_id'];
        }
        $store_ids1=DB::table('stores')->whereIn('user_id', $user_ids)->select('store_id','store_name','id')->get();
        $store_ids1=json_decode($store_ids1,true);
        foreach($store_ids1 as $k=>$v){
            $store_data1[$k]=$v['store_id'];
        }
        if($curHdIndex ==1){
            $where[] = ['created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
            $where[] = ['created_at', '<=', date('Y-m-d', time()).' 23:59:59'];
            //总收款
            $total_amount=DB::table('orders')->whereIn('user_id', $user_ids)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
            //总佣金
            $total_commission='未结算';
            $share_commission='未结算';
            $service_commission='未结算';
            $commission_fee=DB::table('orders')->whereIn('user_id', $user_ids)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount');

            $server_fee=0.00;
            $total_fee=bcadd($commission_fee,$server_fee,2);
            foreach($store_ids as $key=>$val){
                unset($where);
                $where[] = ['orders.created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
                $where[] = ['orders.created_at', '<=', date('Y-m-d', time()).' 23:59:59'];
                $store_arr['store_name']=$val['store_name'];
                $store_arr['store_id']=$val['store_id'];
                $id=$val['id'];
                $result = DB::table('orders')->join('stores', function ($join) {
                    $join->on('orders.store_id', '=', 'stores.store_id');
                })
                    ->whereIn('orders.pay_status', [1, 6])
                    ->where($where)
                    ->where(function ($query) use($id) {
                        $query->where('stores.id', $id)->orwhere('stores.pid', $id);
                        return $query;
                    })
                    ->select([DB::raw('sum(orders.fee_amount) as fee_amount'),DB::raw('sum(orders.rata_money) as rata_money'),DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total'),DB::raw('sum(orders.refund_amount) as refund_amount')])
                    ->first();
                $store_arr['total_amount']=$result->total_amount?$result->total_amount:0.00;
                $store_arr['total_num']=$result->total;
                $store_arr['refund_amount']=$result->refund_amount?$result->refund_amount:0.00;
                $rata_money=$result->rata_money;;
                $fee_amount=$result->fee_amount;;

                $store_arr['fee_amount']=bcadd($rata_money,$fee_amount,2);
                $store_arr['commission_money']='未结算';

                $store_arr_data[]=$store_arr;
            }
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'share_commission'=>$share_commission,
                'service_commission'=>$service_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==2){
            $where[] = ['bill_date', '>=', strtotime('yesterday')];
            $where[] = ['bill_date', '<=', strtotime('yesterday')+86399];
            $where_c[] = ['settling_day', '>=', date('Y-m-d',strtotime("-1 day"))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d',strtotime("-1 day"))];
            $start_date=date('Y-m-d',strtotime("-1 day"));
            $end_date=date('Y-m-d',strtotime("-1 day"));
               //总收款
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $total_amount += $obj->order_amount;
                }
                $total_amount=$total_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=bcsub($total_amount,$refund_amount,2);
            //总佣金
            $start_commission=date('Y-m-d',strtotime("-1 day"));
            $end_commission=date('Y-m-d',strtotime("-1 day"));
            $get_commission=$start_commission.','.$end_commission;
            $total_commission=DB::table('company_day_commission')->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            //分润佣金
            $share_commission=0.00;
            //服务费佣金
            $service_commission=0.00;
            $total_fee=$refund_amount;

            foreach($store_ids as $key=>$val){
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $ways_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $ways_amount_zong += $obj->order_amount;
                    }
                    $ways_amount_zong=$ways_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $refund_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $refund_amount_zong += $obj->refund_amount;
                    }
                    $refund_amount_zong=$refund_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount->unionAll($ways_amount1);
                    $order_total_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $order_total_zong += $obj->order_total;
                    }
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $ways_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('refund_amount')->sum('refund_amount')/100;
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_total')->sum('order_total');
                    
                }
                $total_amount_s=$ways_amount_zong;
                
                $total_num=$order_total_zong;
                
                $fee_amount='0.00';
                
                $commission_money='0.00';
                $refund_amount=$refund_amount_zong;
                $store_arr['store_id']=$val['store_id'];
                $store_arr['store_name']=$val['store_name'];
                $store_arr['total_amount']=$total_amount_s;
                $store_arr['total_num']=$total_num;
                $store_arr['fee_amount']=$fee_amount;
                $store_arr['commission_money']=$commission_money;
                $store_arr['refund_amount']=$refund_amount;
                $store_arr_data[]=$store_arr;
            }
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'share_commission'=>$share_commission,
                'service_commission'=>$service_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
            );
            
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex ==3){
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'))];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime('last week'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime('this week -1 day'))];
            $start_date=date('Y-m-d', strtotime('last week'));
            $end_date=date('Y-m-d', strtotime('this week -1 day'));
              //总收款
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $total_amount += $obj->order_amount;
                }
                $total_amount=$total_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=bcsub($total_amount,$refund_amount,2);
            //总佣金
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            $total_commission=DB::table('company_day_commission')->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            //分润佣金
            $share_commission=0.00;
            //服务费佣金
            $service_commission=0.00;
            $total_fee=$refund_amount;

            foreach($store_ids as $key=>$val){
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $ways_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $ways_amount_zong += $obj->order_amount;
                    }
                    $ways_amount_zong=$ways_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $refund_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $refund_amount_zong += $obj->refund_amount;
                    }
                    $refund_amount_zong=$refund_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount->unionAll($ways_amount1);
                    $order_total_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $order_total_zong += $obj->order_total;
                    }
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $ways_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('refund_amount')->sum('refund_amount')/100;
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_total')->sum('order_total');
                    
                }
                $total_amount_s=$ways_amount_zong;
                
                $total_num=$order_total_zong;
                
                $fee_amount='0.00';
                
                $commission_money='0.00';
                $refund_amount=$refund_amount_zong;
                $store_arr['store_id']=$val['store_id'];
                $store_arr['store_name']=$val['store_name'];
                $store_arr['total_amount']=$total_amount_s;
                $store_arr['total_num']=$total_num;
                $store_arr['fee_amount']=$fee_amount;
                $store_arr['commission_money']=$commission_money;
                $store_arr['refund_amount']=$refund_amount;
                $store_arr_data[]=$store_arr;
            }
                $return_data=array(
                    'total_amount'=>$total_amount,
                    'total_commission'=>$total_commission,
                    'share_commission'=>$share_commission,
                    'service_commission'=>$service_commission,
                    'total_fee'=>$total_fee,
                    'store_company'=>$store_arr_data,
                );
                $this->status = '1';
                $this->message = '数据返回成功';
                return $this->format($return_data);
        }else if($curHdIndex ==4){
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),1,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(0,0,0,date('m'),date('d'),date('Y'))-1];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime("-1 day"))];
            $start_date=date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'));
            $end_date=date('Y-m-d',strtotime("-1 day"));
            // dump($where);die;
                //总收款
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $total_amount += $obj->order_amount;
                }
                $total_amount=$total_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=bcsub($total_amount,$refund_amount,2);
            //总佣金
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            $total_commission=DB::table('company_day_commission')->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            //分润佣金
            $share_commission=0.00;
            //服务费佣金
            $service_commission=0.00;
            $total_fee=$refund_amount;

            foreach($store_ids as $key=>$val){
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $ways_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $ways_amount_zong += $obj->order_amount;
                    }
                    $ways_amount_zong=$ways_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $refund_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $refund_amount_zong += $obj->refund_amount;
                    }
                    $refund_amount_zong=$refund_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount->unionAll($ways_amount1);
                    $order_total_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $order_total_zong += $obj->order_total;
                    }
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $ways_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('refund_amount')->sum('refund_amount')/100;
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_total')->sum('order_total');
                    
                }
                $total_amount_s=$ways_amount_zong;
                
                $total_num=$order_total_zong;
                
                $fee_amount='0.00';
                
                $commission_money='0.00';
                $refund_amount=$refund_amount_zong;
                $store_arr['store_id']=$val['store_id'];
                $store_arr['store_name']=$val['store_name'];
                $store_arr['total_amount']=$total_amount_s;
                $store_arr['total_num']=$total_num;
                $store_arr['fee_amount']=$fee_amount;
                $store_arr['commission_money']=$commission_money;
                $store_arr['refund_amount']=$refund_amount;
                $store_arr_data[]=$store_arr;
            }
                $return_data=array(
                    'total_amount'=>$total_amount,
                    'total_commission'=>$total_commission,
                    'share_commission'=>$share_commission,
                    'service_commission'=>$service_commission,
                    'total_fee'=>$total_fee,
                    'store_company'=>$store_arr_data,
                );
                $this->status = '1';
                $this->message = '数据返回成功';
                return $this->format($return_data);
        }else if($curHdIndex ==5){
            $where[] = ['bill_date', '>=', strtotime(date('Y-m-01 00:00:00',strtotime(date('Y-m-01') . " - 1 month")))];
            $where[] = ['bill_date', '<=', strtotime(date("Y-m-d 23:59:59", strtotime(-date('d').'day')))];
            $where_c[] = ['settling_day', '>=', date('Y-m-01', strtotime('-1 month'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-t', strtotime('-1 month'))];
            $start_date=date('Y-m-01',strtotime(date('Y-m-01') . " - 1 month"));
            $end_date=date("Y-m-d", strtotime(-date('d').'day'));
            //总收款
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $total_amount += $obj->order_amount;
                }
                $total_amount=$total_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $total_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=bcsub($total_amount,$refund_amount,2);
            //总佣金
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            $total_commission=DB::table('company_day_commission')->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');;
            //分润佣金
            $share_commission=0.00;
            //服务费佣金
            $service_commission=0.00;
            $total_fee=$refund_amount;

            foreach($store_ids as $key=>$val){
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $ways_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $ways_amount_zong += $obj->order_amount;
                    }
                    $ways_amount_zong=$ways_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['refund_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $refund_amount_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $refund_amount_zong += $obj->refund_amount;
                    }
                    $refund_amount_zong=$refund_amount_zong/100;
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $val['store_id'])->select(['order_total']);
                    $ways_amount->unionAll($ways_amount1);
                    $order_total_zong=0;
                    foreach ($ways_amount->get() as $obj) {
                        $order_total_zong += $obj->order_total;
                    }
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $ways_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('refund_amount')->sum('refund_amount')/100;
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $val['store_id'])->select('order_total')->sum('order_total');
                    
                }
                $total_amount_s=$ways_amount_zong;
                
                $total_num=$order_total_zong;
                
                $fee_amount='0.00';
                
                $commission_money='0.00';
                $refund_amount=$refund_amount_zong;
                $store_arr['store_id']=$val['store_id'];
                $store_arr['store_name']=$val['store_name'];
                $store_arr['total_amount']=$total_amount_s;
                $store_arr['total_num']=$total_num;
                $store_arr['fee_amount']=$fee_amount;
                $store_arr['commission_money']=$commission_money;
                $store_arr['refund_amount']=$refund_amount;
                $store_arr_data[]=$store_arr;
            }
                $return_data=array(
                    'total_amount'=>$total_amount,
                    'total_commission'=>$total_commission,
                    'share_commission'=>$share_commission,
                    'service_commission'=>$service_commission,
                    'total_fee'=>$total_fee,
                    'store_company'=>$store_arr_data,
                );
                $this->status = '1';
                $this->message = '数据返回成功';
                return $this->format($return_data);
        }
    }
    
    public function view_branch(Request $request){
        $format = [];
        $curHdIndex = $request->get('curHdIndex', '');
        $inputValue=$request->get('inputValue', '');
        $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
        $store_id = $request->get('store_id', '');
        $date_start = $request->get('start_data', '');
        $date_end = $request->get('end_data', '');
        try{
            $login_user = User::where('id', $user_id)->where('is_delete', '=', '0')->first();
            if (!$login_user) {
                throw new \Exception("登录异常");
            }
            switch (intval($curHdIndex)) {
                case 1://今日
                    $date_start = date('Y-m-d 00:00:00');
                    $date_end = date('Y-m-d 23:59:59');
                    break;
                case 2://昨日
                    $date_start = date('Y-m-d 00:00:00', strtotime("-1 day"));
                    $date_end = date('Y-m-d 23:59:59', strtotime("-1 day"));
                    break;
                case 3://上周
                    $date_start = date('Y-m-d 00:00:00', strtotime('last week'));
                    $date_end = date('Y-m-d 23:59:59', strtotime('this week -1 day'));
                    break;
                case 4://本月
                    $date_start = date('Y-m-01 00:00:00');
                    $date_end = date('Y-m-t 23:59:59');
                    break;
                case 5://上月
                    $date_start = date('Y-m-01 00:00:00', strtotime('-1 month', time()));
                    $date_end = date('Y-m-t 23:59:59', strtotime('-1 month', time()));
                    break;
            }
            $time_end = strtotime($date_end);
            $time_start = strtotime($date_start);
            if ($time_end<$date_start){
                throw new \Exception("结束时间不能大于开始时间");
            }
            if ($time_start<strtotime('2023-06-01')){
                throw new \Exception("查询最小时间不能低于2023-06-01");
            }
            if ($time_end>strtotime(date('Y-m-t 23:59:59'))){
                throw new \Exception("查询最大时间不能高于当月");
            }
            $db = DB::connection();
            $user_rates = $db->table('user_rates')->where('user_id', $user_id)->distinct('company')->pluck(DB::raw("CONCAT(server_rate,':',era_rate,':',rate,':',yu_rate)"), 'ways_type')->toArray();
            $monthTotal = $this->getMonthDifference(strtotime($date_start), strtotime($date_end));
            $tableName = 'wft_stores_orders_' . date('Ym', strtotime($date_start)) . '_bill';
            $pluck = DB::connection('old_mysql')->table($tableName)
                ->where('store_id', $store_id)
                ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                ->select([
                    'shop_id',
                    'receive_code',
                    'receive_rate',
                    'receive_model',
                    DB::raw('sum(receive_fee) as receive_fee'),
                    DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                    DB::raw('sum(order_total) as order_total'),
                    DB::raw('sum(order_amount) as order_amount'),
                    DB::raw('sum(refund_total) as refund_total'),
                    DB::raw('sum(refund_amount) as refund_amount'),
                ])
                ->groupBy(Db::raw('shop_id,receive_code,receive_rate,receive_model'));
            for ($i = 0; $i < $monthTotal; $i++) {
                $num = $i + 1;
                $numTime = strtotime("+" . $num . " month", strtotime($date_start));
                $tableName = 'wft_stores_orders_' . date('Ym', $numTime) . '_bill';
                $union_pluck = DB::connection('old_mysql')->table($tableName)
                    ->where('store_id', $store_id)
                    ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                    ->select([
                        'shop_id',
                        'receive_code',
                        'receive_rate',
                        'receive_model',
                        DB::raw('sum(receive_fee) as receive_fee'),
                        DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                        DB::raw('sum(order_total) as order_total'),
                        DB::raw('sum(order_amount) as order_amount'),
                        DB::raw('sum(refund_total) as refund_total'),
                        DB::raw('sum(refund_amount) as refund_amount'),
                    ])
                    ->groupBy(Db::raw('shop_id,receive_code,receive_rate,receive_model'));
                $pluck->unionAll($union_pluck);
            }

            $total_amount='0.00';
            $refund_amount='0.00';
            $total_commission='0.00';
            $total_fee='0.00';
            $shop_list=[];
            foreach ($pluck->get() as $obj) {
                $item = (array)$obj;
                $shop_index = array_search($item['shop_id'],array_column($shop_list,'shop_id'));
                if($shop_index === false){
                    $shop_info = [
                        'store_id'=>$item['shop_id'],
                        'shop_id'=>$item['shop_id'],
                        'store_name'=>'',
                        'total_amount'=>0.00,
                        'total_num'=>0,
                        'refund_amount'=>0.00,
                        'fee_amount'=>0.00,
                        'commission_money'=>0.00,
                    ];
                }else{
                    $shop_info = $shop_list[$shop_index];
                }
                $difference=0.00;

                if(isset($user_rates[$item['receive_code']])){
                    $company_rates = explode(':', $user_rates[$item['receive_code']]);
                    $user_rate = $company_rates[$item['receive_model'] - 1];
//                    if ($user_rate > 0 && $item['receive_rate'] > $user_rate) {
                        $difference = bcmul(bcdiv(bcsub($item['receive_rate'], $user_rate, 2), 100, 4), bcsub($item['order_amount'], $item['refund_amount']), 2);
                        $difference = bcdiv($difference, 100, 2);
//                    }
                }

                $shop_info['total_amount'] = bcadd(bcdiv($item['order_amount'], 100, 2),$shop_info['total_amount'],2);
                $shop_info['total_num'] = bcadd($item['order_total'],$shop_info['total_num']);
                $shop_info['refund_amount'] = bcadd(bcdiv($item['refund_amount'], 100, 2),$shop_info['refund_amount'],2);
                $shop_info['fee_amount'] = bcadd(bcdiv($item['receive_fee'], 100, 2),$shop_info['fee_amount'],2);
                $shop_info['commission_money'] = bcadd($difference,$shop_info['commission_money'],2);

                $total_amount=bcadd(bcdiv($item['order_amount'], 100, 2),$total_amount,2);
                $refund_amount=bcadd(bcdiv($item['refund_amount'], 100, 2),$refund_amount,2);
                $total_commission=bcadd($difference,$total_commission,2);
                $total_fee=bcadd(bcdiv($item['receive_fee'], 100, 2),$total_fee,2);

                if($shop_index === false){
                    $shop_list[] = $shop_info;
                }else{
                    $shop_list[$shop_index] = $shop_info;
                }
            }

            $storeList = $db->table('stores')->whereIn('store_id',array_column($shop_list,'shop_id'))->pluck('store_name','store_id');
            foreach($storeList as $storeId=>$storeName){
                $shop_index = array_search($storeId,array_column($shop_list,'shop_id'));
                if($shop_index!==false){
                    $shop_list[$shop_index]['store_name'] = $storeName;
                }
            }

            $format = [
                'total_amount' => bcsub($total_amount, $refund_amount, 2),
                'total_commission' => $total_commission,
                'total_fee' => $total_fee,
                'store_company' => $shop_list,
                'start_date' => $date_start,
                'end_date' => $date_end,
                'time' => implode(' - ', [$date_start, $date_end])
            ];
            $this->status = 1;
            $this->message = 'Ok';
        } catch (\Exception $e) {
            $this->status = 2;
            $this->message = $e->getMessage();
        }
        return $this->format($format);
    }
    
    /**
     * 查看分店
     * 2022-04-20 10:26
     */
    public function _view_branch(Request $request){
        $token = $this->parseToken();
        $token_user_id = $token->user_id;
        $curHdIndex=$request->get('curHdIndex', '');
        $start_data = $request->get('start_data', '');
        $end_data = $request->get('end_data', '');
        $store_id = $request->get('store_id', '');
        
        
        $store = DB::table('stores')->where('store_id', $store_id)->select('store_id', 'store_name', 'id')->first(); // 查找总店
        $p_stores = DB::table('stores')->where('pid', $store->id)->select('store_id')->get(); // 查找总店下的分店
        if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
            $p_store_data[0] = $store->store_id;
            $p_stores = json_decode($p_stores, true);
            foreach($p_stores as $k1 => $v1){
                $p_store_data[] = $v1['store_id'];
            }
        }else{
            $p_store_data[0] = $store->store_id;
        }
        if($curHdIndex == 1){ // 今日
            $where[] = ['created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
            $where[] = ['created_at', '<=', date('Y-m-d', time()).' 23:59:59'];
            $start_date=date('Y-m-d', time());
            $end_date=date('Y-m-d', time());
            $total_amount = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount'); // 总收款
            $total_commission = '待结算'; // 总佣金
            $total_fee = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('refund_amount')->sum('refund_amount'); // 总手续费
            // $total_fee = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('fee_amount')->sum('fee_amount'); // 总手续费
            // $total_fee = $total_fee + $rata_money;
            foreach($p_store_data as $key => $val){
                $store = DB::table('stores')->where('store_id', $val)->select('rata_status', 'store_name', 'store_id')->first();
                $data[$key]['store_id'] = $store->store_id;
                $data[$key]['store_name'] = $store->store_name;
                // $data[$key]['store_name'] = DB::table('stores')->where('store_id', $val)->value('store_name');
                $data[$key]['total_amount'] = DB::table('orders')->where('store_id', $val)->where($where)->whereIn('pay_status', [1, 6])->select()->sum('total_amount'); // 门店总金额
                $data[$key]['total_num'] = DB::table('orders')->where('store_id', $val)->where($where)->whereIn('pay_status', [1, 6])->select()->count('total_amount'); // 门店总笔数
                $data[$key]['refund_amount'] = DB::table('orders')->where('store_id', $val)->where($where)->whereIn('pay_status', [6])->select()->sum('total_amount'); // 门店退款金额
                // if( $store->rata_status > 0 ){
                    $data[$key]['rata_money'] = DB::table('orders')->where('store_id', $val)->where($where)->whereIn('pay_status', [1])->select()->sum('rata_money');
                // }else{
                    $data[$key]['fee_amount'] = DB::table('orders')->where('store_id', $val)->where($where)->whereIn('pay_status', [1])->select()->sum('fee_amount');
                    $data[$key]['fee_amount'] = $data[$key]['fee_amount'] + $data[$key]['rata_money'];
                // }
                $data[$key]['commission_money'] = '未结算';
            }
            array_multisort( array_column($data, 'total_amount'), SORT_DESC, $data );
            // dump( $data );die;
            $return_data = array(
                'total_amount' => $total_amount,
                'total_commission' => $total_commission,
                'total_fee' => $total_fee,
                'store_company' => $data,
                'start_date' => $start_date,
                'end_date' => $end_date,
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }
        if($curHdIndex == 2){
            $where[] = ['bill_date', '>=', strtotime('yesterday')];
            $where[] = ['bill_date', '<=', strtotime('yesterday')+86399];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime("-1 day"))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime("-1 day"))];
            $start_date=date('Y-m-d', strtotime("-1 day"));
            $end_date=date('Y-m-d', strtotime("-1 day"));
        }else if($curHdIndex == 3){ // 上周
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'))];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime('last week'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime('this week -1 day'))];
            $start_date=date('Y-m-d', strtotime('last week'));
            $end_date=date('Y-m-d', strtotime('this week -1 day'));
        }else if($curHdIndex == 4){ // 本月
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),1,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(0,0,0,date('m'),date('d'),date('Y'))-1];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime("-1 day"))];
            $start_date=date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'));
            $end_date=date('Y-m-d', strtotime("-1 day"));
        }else if($curHdIndex == 5){ // 上月
            $where[] = ['bill_date', '>=', strtotime(date('Y-m-01 00:00:00',strtotime(date('Y-m-01') . " - 1 month")))];
            $where[] = ['bill_date', '<=', strtotime(date("Y-m-d 23:59:59", strtotime(-date('d').'day')))];
            $where_c[] = ['settling_day', '>=', date('Y-m-01', strtotime('-1 month'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-t', strtotime('-1 month'))];
            $start_date=date('Y-m-01', strtotime(date('Y-m-01') . " - 1 month"));
            $end_date=date('Y-m-t', strtotime('-1 month'));
        }else if($curHdIndex == 6){ // 
            $start_date=$start_data;
            $end_date=$end_data;
            $where[] = ['bill_date', '>=', strtotime($start_data.' 00:00:00')];
            $where[] = ['bill_date', '<=', strtotime($end_data.' 23:59:59')];
            $where_c[] = ['settling_day', '>=', $start_data];
            $where_c[] = ['settling_day', '<=', $end_data];
            
            if ($start_data != $end_data) {
                $date = ((strtotime($end_data) > strtotime($start_data)))?true:false;
                if (!$date) {
                    $this->status = '2';
                    $this->message = '开始时间不能超过结束时间';
                    return $this->format(2);
                }
            }
            // //限制时间
            $date = (strtotime($end_data) - strtotime($start_data)) / 86400;
            $day = 31;
            if ($date > $day) {
                $this->status = '2';
                $this->message = "时间筛选不能超过 $day 天";
                return $this->format(2);
            }
        }
        if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
            $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
            $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
            $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['order_amount']);
            $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['order_amount']);
            $ways_amount->unionAll($ways_amount1);
            $store_amount=0;
            foreach ($ways_amount->get() as $obj) {
                $store_amount += $obj->order_amount;
            }
            $store_amount=$store_amount/100;
            
            $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
            $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
            $refund_amount_zong->unionAll($refund_amount1);
            $refund_amount=0;
            foreach ($refund_amount_zong->get() as $obj) {
                $refund_amount += $obj->refund_amount;
            }
            $refund_amount=$refund_amount/100;
        }else{
            $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
            $store_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
            $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
        }
        
        $total_amount=$store_amount;
        
        $start_commission=$start_date;
        $end_commission=$end_date;
        $get_commission=$start_commission.','.$end_commission;
        if(count($p_store_data)>100){
            $total_commission=DB::table('company_day_commission')->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
        }else{
            $total_commission=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
        }
        $total_fee=$refund_amount;
        
        foreach($p_store_data as $key => $val){
            $store = DB::table('stores')->where('store_id', $val)->select('rata_status', 'store_name', 'store_id')->first();
            $data[$key]['store_id'] = $store->store_id;
            $data[$key]['store_name'] = $store->store_name;
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$val)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('shop_id',$val)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $store_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $store_amount += $obj->order_amount;
                }
                $store_amount=$store_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$val)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('shop_id',$val)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
                
                $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$val)->select(['order_total']);
                $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->where('shop_id',$val)->select(['order_total']);
                $order_total_zong->unionAll($order_total_zong1);
                $order_total=0;
                foreach ($order_total_zong->get() as $obj) {
                    $order_total += $obj->order_total;
                }
                
                $receive_fee_zong=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$val)->select(['refund_amount']);
                $receive_fee_zong1=DB::connection('old_mysql')->table($table1)->where($where)->where('shop_id',$val)->select(['refund_amount']);
                $receive_fee_zong->unionAll($receive_fee_zong1);
                $receive_fee=0;
                foreach ($receive_fee_zong->get() as $obj) {
                    $receive_fee += $obj->refund_amount;
                }
                $receive_fee=$receive_fee/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $store_amount=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$val)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$val)->select('refund_amount')->sum('refund_amount')/100;
                $order_total=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$val)->select('order_total')->sum('order_total');
                $receive_fee=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$val)->select('receive_fee')->sum('receive_fee')/100;
            }
            // $merchant_amount=DB::connection('old_mysql')->table('wft_stores_orders_202307_bill')->where('shop_id', $val)->where($where)->select('order_amount')->sum('order_amount')/100;
            // $merchant_amount1=DB::connection('old_mysql')->table('wft_stores_orders_202306_bill')->where('shop_id', $val)->where($where)->select('order_amount')->sum('order_amount')/100;
            $data[$key]['total_amount'] =$store_amount; // 门店总金额
            
            
            $data[$key]['total_num']=$order_total;  // 门店总笔数
            
            $data[$key]['refund_amount']=$refund_amount; // 门店退款金额
            $data[$key]['fee_amount']=$receive_fee;
            $data[$key]['commission_money'] ='0.00'; // 佣金
        }
        array_multisort( array_column($data, 'total_amount'), SORT_DESC, $data );
        // dump($data);die;
        $return_data = array(
            'total_amount' => $total_amount,
            'total_commission' => $total_commission,
            'total_fee' => $total_fee,
            'start_date' => $start_date,
            'end_date' => $end_date,
            'store_company' => $data,
        );
        $this->status = '1';
        $this->message = '数据返回成功';
        return $this->format($return_data);
    }
    
    public function commission_store_company(Request $request){
        $format = [];
        $curHdIndex = $request->get('curHdIndex', '');
        $store_id = $request->get('store_id', '');
        $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
        $date_start = $request->get('start_date', '');
        $date_end = $request->get('end_date', '');
        try {
            switch (intval($curHdIndex)) {
                case 1://今日
                    $date_start = date('Y-m-d 00:00:00');
                    $date_end = date('Y-m-d 23:59:59');
                    break;
                case 2://昨日
                    $date_start = date('Y-m-d 00:00:00', strtotime("-1 day"));
                    $date_end = date('Y-m-d 23:59:59', strtotime("-1 day"));
                    break;
                case 3://上周
                    $date_start = date('Y-m-d 00:00:00', strtotime('last week'));
                    $date_end = date('Y-m-d 23:59:59', strtotime('this week -1 day'));
                    break;
                case 4://本月
                    $date_start = date('Y-m-01 00:00:00');
                    $date_end = date('Y-m-t 23:59:59');
                    break;
                case 5://上月
                    $date_start = date('Y-m-01 00:00:00', strtotime('-1 month', time()));
                    $date_end = date('Y-m-t 23:59:59', strtotime('-1 month', time()));
                    break;
            }
            $time_end = strtotime($date_end);
            $time_start = strtotime($date_start);
            if ($time_end<$date_start){
                throw new \Exception("结束时间不能大于开始时间");
            }
            if ($time_start<strtotime('2023-06-01')){
                throw new \Exception("查询最小时间不能低于2023-06-01");
            }
            if ($time_end>strtotime(date('Y-m-t 23:59:59'))){
                throw new \Exception("查询最大时间不能高于当天");
            }
            $db = DB::connection();

            $fee_amount = '0.00';
            $total_amount = '0.00';
            $refund_amount = '0.00';
            $commission_money = '0.00';

            $store_rates = $db->table('store_pay_ways')->where('store_id', $store_id)->groupBy('company')->pluck(DB::raw("GROUP_CONCAT(ways_type)"), 'company')->toArray();
            $user_rates = $db->table('user_rates')->where('user_id', $user_id)->distinct('company')->pluck(DB::raw("CONCAT(server_rate,':',era_rate,':',rate,':',yu_rate)"), 'company')->toArray();
            $company_list = $db->table('store_all_pay_way_lists')->whereIn('company', array_keys(array_merge($store_rates,$user_rates)))->pluck('company_desc', 'company')->toArray();

            $merchant_list = [];
            if (is_array($store_rates)) {
                $monthTotal = $this->getMonthDifference(strtotime($date_start), strtotime($date_end));

                foreach ($store_rates as $company => $ways_type) {
                    if(!isset($company_list[$company])){
                        continue;
                    }
                    $company_amount = '0.00';
                    $company_total = 0;
                    $company_refund = '0.00';
                    $company_fee = '0.00';
                    $company_commission = '0.00';
                    $company_name = $company_list[$company];
                    $company_rates = explode(':', $user_rates[$company]);
                    $explode = explode(',', $ways_type);
                    $tableName = 'wft_stores_orders_' . date('Ym', strtotime($date_start)) . '_bill';
                    $pluck = DB::connection('old_mysql')->table($tableName)
                        ->where('store_id', $store_id)
                        ->whereIn('receive_code', $explode)
                        ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                        ->select([
                            'receive_rate',
                            'receive_model',
                            DB::raw('sum(receive_fee) as receive_fee'),
                            DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                            DB::raw('sum(order_total) as order_total'),
                            DB::raw('sum(order_amount) as order_amount'),
                            DB::raw('sum(refund_total) as refund_total'),
                            DB::raw('sum(refund_amount) as refund_amount'),
                        ])
                        ->groupBy(Db::raw('receive_rate,receive_model'));
                    for ($i = 0; $i < $monthTotal; $i++) {
                        $num = $i + 1;
                        $numTime = strtotime("+" . $num . " month", strtotime($date_start));
                        $tableName = 'wft_stores_orders_' . date('Ym', $numTime) . '_bill';
                        $union_pluck = DB::connection('old_mysql')->table($tableName)
                            ->where('store_id', $store_id)
                            ->whereIn('receive_code', $explode)
                            ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                            ->select([
                                'receive_rate',
                                'receive_model',
                                DB::raw('sum(receive_fee) as receive_fee'),
                                DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                                DB::raw('sum(order_total) as order_total'),
                                DB::raw('sum(order_amount) as order_amount'),
                                DB::raw('sum(refund_total) as refund_total'),
                                DB::raw('sum(refund_amount) as refund_amount'),
                            ])
                            ->groupBy(Db::raw('receive_rate,receive_model'));
                        $pluck->unionAll($union_pluck);
                    }
                    foreach ($pluck->get() as $obj) {
                        $item = (array)$obj;
                        $user_rate = $company_rates[$item['receive_model'] - 1];
//                        if ($user_rate > 0 && $item['receive_rate'] > $user_rate) {
                            $difference = bcmul(bcdiv(bcsub($item['receive_rate'], $user_rate, 2), 100, 4), bcsub($item['order_amount'], $item['refund_amount']), 2);
                            $difference = bcdiv($difference, 100, 2);
                            $company_commission = bcadd($company_commission, $difference, 2);
//                        }
                        $company_amount = bcadd($company_amount, bcdiv($item['order_amount'], 100, 2), 2);
                        $company_total = bcadd($company_total, $item['order_total']);
                        $company_refund = bcadd($company_refund, bcdiv($item['refund_amount'], 100, 2), 2);
                        $company_fee = bcadd($company_fee, bcdiv($item['receive_fee'] - $item['receive_refund_fee'], 100, 2), 2);
                    }
                    $merchant_list[] = [
                        'company_name' => $company_name,
                        'total_amount' => $company_amount,
                        'total_num' => $company_total,
                        'refund_amount' => $company_refund,
                        'fee_amount' => $company_fee,
                        'commission_money' => $company_commission,
                    ];
                    $total_amount = bcadd($total_amount, $company_amount, 2);
                    $refund_amount = bcadd($refund_amount, $company_refund, 2);
                    $fee_amount = bcadd($fee_amount, $company_fee, 2);
                    $commission_money = bcadd($commission_money, $company_commission, 2);
                }
            }
            $format = [
                'total_amount' => bcsub($total_amount, $refund_amount, 2),
                'total_commission' => $commission_money,
                'total_fee' => $fee_amount,
                'refund_amount' => $refund_amount,
                'store_company' => $merchant_list,
                'store_name'=> DB::table('stores')->where('store_id',$store_id)->value('store_name'),
                'start_date' => $date_start,
                'end_date' => $date_end,
                'time' => implode(' - ', [$date_start, $date_end])
            ];
            $this->status = 1;
            $this->message = 'Ok';
        } catch (\Exception $e) {
            $this->status = 2;
            $this->message = $e->getMessage();
        }
        return $this->format($format);
    }

    public function _commission_store_company(Request $request){
        $token = $this->parseToken();
        $token_user_id = $token->user_id;
        $curHdIndex=$request->get('curHdIndex', '');
        $start_data=$request->get('start_data', '');
        $end_data=$request->get('end_data', '');
        $store_id=$request->get('store_id', '');
        // $user_ids = $this->getSubIds($token_user_id);
        
        $store=DB::table('stores')->where('store_id', $store_id)->select('store_id','store_name','id')->first();
        $p_stores=DB::table('stores')->where('pid',$store->id)->select('store_id')->get();
        if(!empty($p_stores[0]->store_id)){
            $p_store_data[0]=$store->store_id;
            $p_stores=json_decode($p_stores,true);
            foreach($p_stores as $k1=>$v1){
                $p_store_data[]=$v1['store_id'];
            }
        }else{
            $p_store_data[0]=$store->store_id;
        }
        if($curHdIndex==1){
            $where[] = ['created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
            $where[] = ['created_at', '<=', date('Y-m-d', time()).' 23:59:59'];
            $start_date=date('Y-m-d', time());
            $end_date=date('Y-m-d', time());
            //总收款
            $total_amount=Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
            //总佣金
            $total_commission='待结算';
            $total_fee=Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('refund_amount')->sum('refund_amount');
            $pay_ways=DB::table('store_pay_ways')->where('store_id', $store_id)->select('company')->distinct()->get();
            foreach($pay_ways as $k=>$v){
                if($v->company=='wftpay'){
                    $company_name='徽商银行';
                }else if($v->company=='wingpay'){
                    $company_name='翼支付';
                }else if($v->company=='vbill'){
                    $company_name='随行付';
                }else if($v->company=='alipay'){
                    $company_name='支付宝官方';
                }else if($v->company=='weixin'){
                    $company_name='微信官方';
                }else if($v->company=='hwcpay'){
                    $company_name='汇旺财';
                }else if($v->company=='nongjin'){
                    $company_name='农商行';
                }else if($v->company=='abc'){
                    $company_name='农行';
                }else if($v->company=='pingan'){
                    $company_name='平安银行';
                }else if($v->company=='jiujiang'){
                    $company_name='九江银行';
                }else if($v->company=='lianfuyoupay'){
                    $company_name='邮储银行';
                }else{
                    $company_name=$v->company;
                }
                $store_arr['company_name']=$company_name;
                $store_arr['store_id']=$store->store_id;
                $store_arr['total_amount']=Order::whereIn('store_id', $p_store_data)->where($where)->where('company',$v->company)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
                $store_arr['total_num']=Order::whereIn('store_id', $p_store_data)->where($where)->where('company',$v->company)->whereIn('pay_status', [1, 6])->select('total_amount')->count('total_amount');
                $store_arr['refund_amount']=Order::whereIn('store_id', $p_store_data)->where($where)->where('company',$v->company)->whereIn('pay_status', [1, 6])->select('refund_amount')->sum('refund_amount');
                $store_arr['fee_amount']=Order::whereIn('store_id', $p_store_data)->where($where)->where('company',$v->company)->whereIn('pay_status', [1, 6])->select('fee_amount')->sum('fee_amount');
                $store_arr['commission_money']='待结算';
                $store_arr_data[]=$store_arr;
            }
            array_multisort( array_column($store_arr_data, 'total_amount'), SORT_DESC, $store_arr_data );
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
                'store_name'=>$store->store_name,
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'time'=>date('Y-m-d', time()).' 00:00:00'.'-'.date('Y-m-d', time()).' 23:59:59'
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex==2){
            $where[] = ['bill_date', '>=', strtotime('yesterday')];
            $where[] = ['bill_date', '<=', strtotime('yesterday')+86399];
            $where_c[] = ['settling_day', '>=', date('Y-m-d',strtotime("-1 day"))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d',strtotime("-1 day"))];
            $start_date=date('Y-m-d',strtotime("-1 day"));
            $end_date=date('Y-m-d',strtotime("-1 day"));
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $store_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $store_amount += $obj->order_amount;
                }
                $store_amount=$store_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $store_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=$store_amount;
            //总佣金
            $get_commission=$start_date.','.$end_date;
            if(count($p_store_data)>100){
                $total_commission=DB::table('company_day_commission')->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }else{
                $total_commission=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }
            $total_fee=$refund_amount;
            $pay_ways=DB::table('store_pay_ways')->where('store_id', $store_id)->select('company')->distinct()->get();
            foreach($pay_ways as $k=>$v){
                if($v->company=='wftpay'){
                    $company_name='徽商银行';
                }else if($v->company=='wingpay'){
                    $company_name='翼支付';
                }else if($v->company=='vbill'){
                    $company_name='随行付';
                }else if($v->company=='alipay'){
                    $company_name='支付宝官方';
                }else if($v->company=='weixin'){
                    $company_name='微信官方';
                }else if($v->company=='hwcpay'){
                    $company_name='汇旺财';
                }else if($v->company=='nongjin'){
                    $company_name='农商行';
                }else if($v->company=='abc'){
                    $company_name='农行';
                }else if($v->company=='pingan'){
                    $company_name='平安银行';
                }else if($v->company=='lianfuyoupay'){
                    $company_name='邮储银行';
                }else if($v->company=='jiujiang'){
                    $company_name='九江银行';
                }else{
                    $company_name=$v->company;
                }
                $store_arr['company_name']=$company_name;
                $store_arr['store_id']=$store->store_id;
                
                $company_ways=DB::table('store_ways_desc')->where('company', $v->company)->select('ways_type as receive_code')->get();
                $company_ways=json_decode($company_ways,true);
                unset($pluckArray);
                foreach ($company_ways as $key1=>$val1){
                    $pluckArray[$key1]=$val1['receive_code'];
                }
                // 总金额
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $store_amount_company=0;
                    foreach ($ways_amount->get() as $obj) {
                        $store_amount_company += $obj->order_amount;
                    }
                    $store_amount_company=$store_amount_company/100;
                    
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount_zong->unionAll($refund_amount1);
                    $refund_amount_company=0;
                    foreach ($refund_amount_zong->get() as $obj) {
                        $refund_amount_company += $obj->refund_amount;
                    }
                    $refund_amount_company=$refund_amount_company/100;
                    
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong->unionAll($order_total_zong1);
                    $order_total=0;
                    foreach ($order_total_zong->get() as $obj) {
                        $order_total += $obj->order_total;
                    }
                    
                    $receive_fee_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong->unionAll($receive_fee_zong1);
                    $receive_fee=0;
                    foreach ($receive_fee_zong->get() as $obj) {
                        $receive_fee += $obj->receive_fee;
                    }
                    $receive_fee=$receive_fee/100;
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $store_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
                    $order_total=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_total')->sum('order_total');
                    $receive_fee=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('receive_fee')->sum('receive_fee')/100;
                }
                $store_arr['total_amount']=$store_amount_company;
                $store_arr['total_num']=$order_total;
                if(count($p_store_data)>100){
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }else{
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }
                $store_arr['commission_money']= $company_day_commission;
                $store_arr['fee_amount']=$receive_fee;
                $store_arr['refund_amount']=$refund_amount_company;
                $store_arr_data[]=$store_arr;
            }
            array_multisort( array_column($store_arr_data, 'total_amount'), SORT_DESC, $store_arr_data );
            
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
                'store_name'=>$store->store_name,
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'time'=>date('Y-m-d',strtotime("-1 day")).'-'.date('Y-m-d',strtotime("-1 day"))
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex==3){
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'))];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime('last week'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime('this week -1 day'))];
            $start_date=date('Y-m-d', strtotime('last week'));
            $end_date=date('Y-m-d', strtotime('this week -1 day'));
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $store_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $store_amount += $obj->order_amount;
                }
                $store_amount=$store_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $store_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=$store_amount;
            //总佣金
            $get_commission=$start_date.','.$end_date;
            if(count($p_store_data)>100){
                $total_commission=DB::table('company_day_commission')->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }else{
                $total_commission=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }
            $total_fee=$refund_amount;
            $pay_ways=DB::table('store_pay_ways')->where('store_id', $store_id)->select('company')->distinct()->get();
            foreach($pay_ways as $k=>$v){
                if($v->company=='wftpay'){
                    $company_name='徽商银行';
                }else if($v->company=='wingpay'){
                    $company_name='翼支付';
                }else if($v->company=='vbill'){
                    $company_name='随行付';
                }else if($v->company=='alipay'){
                    $company_name='支付宝官方';
                }else if($v->company=='weixin'){
                    $company_name='微信官方';
                }else if($v->company=='hwcpay'){
                    $company_name='汇旺财';
                }else if($v->company=='nongjin'){
                    $company_name='农商行';
                }else if($v->company=='abc'){
                    $company_name='农行';
                }else if($v->company=='pingan'){
                    $company_name='平安银行';
                }else if($v->company=='jiujiang'){
                    $company_name='九江银行';
                }else if($v->company=='lianfuyoupay'){
                    $company_name='邮储银行';
                }else{
                    $company_name=$v->company;
                }
                $store_arr['company_name']=$company_name;
                $store_arr['store_id']=$store->store_id;
                
                $company_ways=DB::table('store_ways_desc')->where('company', $v->company)->select('ways_type as receive_code')->get();
                $company_ways=json_decode($company_ways,true);
                unset($pluckArray);
                foreach ($company_ways as $key1=>$val1){
                    $pluckArray[$key1]=$val1['receive_code'];
                }
                // 总金额
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $store_amount_company=0;
                    foreach ($ways_amount->get() as $obj) {
                        $store_amount_company += $obj->order_amount;
                    }
                    $store_amount_company=$store_amount_company/100;
                    
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount_zong->unionAll($refund_amount1);
                    $refund_amount_company=0;
                    foreach ($refund_amount_zong->get() as $obj) {
                        $refund_amount_company += $obj->refund_amount;
                    }
                    $refund_amount_company=$refund_amount_company/100;
                    
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong->unionAll($order_total_zong1);
                    $order_total=0;
                    foreach ($order_total_zong->get() as $obj) {
                        $order_total += $obj->order_total;
                    }
                    
                    $receive_fee_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong->unionAll($receive_fee_zong1);
                    $receive_fee=0;
                    foreach ($receive_fee_zong->get() as $obj) {
                        $receive_fee += $obj->receive_fee;
                    }
                    $receive_fee=$receive_fee/100;
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $store_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
                    $order_total=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_total')->sum('order_total');
                    $receive_fee=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('receive_fee')->sum('receive_fee')/100;
                }
                $store_arr['total_amount']=$store_amount_company;
                $store_arr['total_num']=$order_total;
                if(count($p_store_data)>100){
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }else{
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }
                $store_arr['commission_money']= $company_day_commission;
                $store_arr['fee_amount']=$receive_fee;
                $store_arr['refund_amount']=$refund_amount_company;
                $store_arr_data[]=$store_arr;
            }
            array_multisort( array_column($store_arr_data, 'total_amount'), SORT_DESC, $store_arr_data );
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
                'store_name'=>$store->store_name,
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'time'=>date('Y-m-d', strtotime('last week')).'-'.date('Y-m-d', strtotime('this week -1 day'))
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex==4){
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),1,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(0,0,0,date('m'),date('d'),date('Y'))-1];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d',strtotime("-1 day"))];
            $start_date=date('Y-m-d', strtotime('last week'));
            $end_date=date('Y-m-d', strtotime('this week -1 day'));
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $store_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $store_amount += $obj->order_amount;
                }
                $store_amount=$store_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $store_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=$store_amount;
            //总佣金
            $get_commission=$start_date.','.$end_date;
            if(count($p_store_data)>100){
                $total_commission=DB::table('company_day_commission')->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }else{
                $total_commission=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }
            $total_fee=$refund_amount;
            $pay_ways=DB::table('store_pay_ways')->where('store_id', $store_id)->select('company')->distinct()->get();
            foreach($pay_ways as $k=>$v){
                if($v->company=='wftpay'){
                    $company_name='徽商银行';
                }else if($v->company=='wingpay'){
                    $company_name='翼支付';
                }else if($v->company=='vbill'){
                    $company_name='随行付';
                }else if($v->company=='alipay'){
                    $company_name='支付宝官方';
                }else if($v->company=='weixin'){
                    $company_name='微信官方';
                }else if($v->company=='hwcpay'){
                    $company_name='汇旺财';
                }else if($v->company=='nongjin'){
                    $company_name='农商行';
                }else if($v->company=='abc'){
                    $company_name='农行';
                }else if($v->company=='pingan'){
                    $company_name='平安银行';
                }else if($v->company=='jiujiang'){
                    $company_name='九江银行';
                }else if($v->company=='lianfuyoupay'){
                    $company_name='邮储银行';
                }else{
                    $company_name=$v->company;
                }
                $store_arr['company_name']=$company_name;
                $store_arr['store_id']=$store->store_id;
                
                $company_ways=DB::table('store_ways_desc')->where('company', $v->company)->select('ways_type as receive_code')->get();
                $company_ways=json_decode($company_ways,true);
                unset($pluckArray);
                foreach ($company_ways as $key1=>$val1){
                    $pluckArray[$key1]=$val1['receive_code'];
                }
                // 总金额
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $store_amount_company=0;
                    foreach ($ways_amount->get() as $obj) {
                        $store_amount_company += $obj->order_amount;
                    }
                    $store_amount_company=$store_amount_company/100;
                    
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount_zong->unionAll($refund_amount1);
                    $refund_amount_company=0;
                    foreach ($refund_amount_zong->get() as $obj) {
                        $refund_amount_company += $obj->refund_amount;
                    }
                    $refund_amount_company=$refund_amount_company/100;
                    
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong->unionAll($order_total_zong1);
                    $order_total=0;
                    foreach ($order_total_zong->get() as $obj) {
                        $order_total += $obj->order_total;
                    }
                    
                    $receive_fee_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong->unionAll($receive_fee_zong1);
                    $receive_fee=0;
                    foreach ($receive_fee_zong->get() as $obj) {
                        $receive_fee += $obj->receive_fee;
                    }
                    $receive_fee=$receive_fee/100;
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $store_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
                    $order_total=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_total')->sum('order_total');
                    $receive_fee=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('receive_fee')->sum('receive_fee')/100;
                }
                $store_arr['total_amount']=$store_amount_company;
                $store_arr['total_num']=$order_total;
                if(count($p_store_data)>100){
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }else{
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }
                $store_arr['commission_money']= $company_day_commission;
                $store_arr['fee_amount']=$receive_fee;
                $store_arr['refund_amount']=$refund_amount_company;
                $store_arr_data[]=$store_arr;
            }
            array_multisort( array_column($store_arr_data, 'total_amount'), SORT_DESC, $store_arr_data );
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
                'store_name'=>$store->store_name,
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'time'=>date('Y-m-d', strtotime('last week')).'-'.date('Y-m-d', strtotime('this week -1 day'))
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex==5){
            $where[] = ['bill_date', '>=', strtotime(date('Y-m-01 00:00:00',strtotime(date('Y-m-01') . " - 1 month")))];
            $where[] = ['bill_date', '<=', strtotime(date("Y-m-d 23:59:59", strtotime(-date('d').'day')))];
            $where_c[] = ['settling_day', '>=', date('Y-m-01', strtotime('-1 month'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-t', strtotime('-1 month'))];
            $start_date=date('Y-m-01', strtotime(date('Y-m-01') . " - 1 month"));
            $end_date=date('Y-m-t', strtotime('-1 month'));
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $store_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $store_amount += $obj->order_amount;
                }
                $store_amount=$store_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $store_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=$store_amount;
            //总佣金
            $get_commission=$start_date.','.$end_date;
            if(count($p_store_data)>100){
                $total_commission=DB::table('company_day_commission')->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }else{
                $total_commission=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }
            $total_fee=$refund_amount;
            $pay_ways=DB::table('store_pay_ways')->where('store_id', $store_id)->select('company')->distinct()->get();
            foreach($pay_ways as $k=>$v){
                if($v->company=='wftpay'){
                    $company_name='徽商银行';
                }else if($v->company=='wingpay'){
                    $company_name='翼支付';
                }else if($v->company=='vbill'){
                    $company_name='随行付';
                }else if($v->company=='alipay'){
                    $company_name='支付宝官方';
                }else if($v->company=='weixin'){
                    $company_name='微信官方';
                }else if($v->company=='hwcpay'){
                    $company_name='汇旺财';
                }else if($v->company=='nongjin'){
                    $company_name='农商行';
                }else if($v->company=='abc'){
                    $company_name='农行';
                }else if($v->company=='pingan'){
                    $company_name='平安银行';
                }else if($v->company=='jiujiang'){
                    $company_name='九江银行';
                }else if($v->company=='lianfuyoupay'){
                    $company_name='邮储银行';
                }else{
                    $company_name=$v->company;
                }
                $store_arr['company_name']=$company_name;
                $store_arr['store_id']=$store->store_id;
                
                $company_ways=DB::table('store_ways_desc')->where('company', $v->company)->select('ways_type as receive_code')->get();
                $company_ways=json_decode($company_ways,true);
                unset($pluckArray);
                foreach ($company_ways as $key1=>$val1){
                    $pluckArray[$key1]=$val1['receive_code'];
                }
                // 总金额
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $store_amount_company=0;
                    foreach ($ways_amount->get() as $obj) {
                        $store_amount_company += $obj->order_amount;
                    }
                    $store_amount_company=$store_amount_company/100;
                    
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount_zong->unionAll($refund_amount1);
                    $refund_amount_company=0;
                    foreach ($refund_amount_zong->get() as $obj) {
                        $refund_amount_company += $obj->refund_amount;
                    }
                    $refund_amount_company=$refund_amount_company/100;
                    
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong->unionAll($order_total_zong1);
                    $order_total=0;
                    foreach ($order_total_zong->get() as $obj) {
                        $order_total += $obj->order_total;
                    }
                    
                    $receive_fee_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong->unionAll($receive_fee_zong1);
                    $receive_fee=0;
                    foreach ($receive_fee_zong->get() as $obj) {
                        $receive_fee += $obj->receive_fee;
                    }
                    $receive_fee=$receive_fee/100;
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $store_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
                    $order_total=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_total')->sum('order_total');
                    $receive_fee=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('receive_fee')->sum('receive_fee')/100;
                }
                $store_arr['total_amount']=$store_amount_company;
                $store_arr['total_num']=$order_total;
                if(count($p_store_data)>100){
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }else{
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }
                $store_arr['commission_money']= $company_day_commission;
                $store_arr['fee_amount']=$receive_fee;
                $store_arr['refund_amount']=$refund_amount_company;
                $store_arr_data[]=$store_arr;
            }
            array_multisort( array_column($store_arr_data, 'total_amount'), SORT_DESC, $store_arr_data );
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
                'store_name'=>$store->store_name,
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'time'=>date('Y-m-d', strtotime('last week')).'-'.date('Y-m-d', strtotime('this week -1 day'))
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if( $curHdIndex==6){
            $start_data = $request->get('start_data', '');
            $end_data = $request->get('end_data', '');
            $start_date=$start_data;
            $end_date=$end_data;
            
            if ($start_data != $end_data) {
                $date = ((strtotime($end_data) > strtotime($start_data)))?true:false;
                if (!$date) {
                    $this->status = '2';
                    $this->message = '开始时间不能超过结束时间';
                    return $this->format(2);
                }
            }
            // //限制时间
            $date = (strtotime($end_data) - strtotime($start_data)) / 86400;
            $day = 31;
            if ($date > $day) {
                $this->status = '2';
                $this->message = "时间筛选不能超过 $day 天";
                return $this->format(2);
            }
            
            $where[] = ['bill_date', '>=', strtotime($start_data.' 00:00:00')];
            $where[] = ['bill_date', '<=', strtotime($end_data.' 23:59:59')];
            $where_c[] = ['settling_day', '>=', $start_data];
            $where_c[] = ['settling_day', '<=', $end_data];
            
            // dump($where);die;
            
           if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $store_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $store_amount += $obj->order_amount;
                }
                $store_amount=$store_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $store_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=$store_amount;
            //总佣金
            $get_commission=$start_date.','.$end_date;
            if(count($p_store_data)>100){
                $total_commission=DB::table('company_day_commission')->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }else{
                $total_commission=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }
            $total_fee=$refund_amount;
            $pay_ways=DB::table('store_pay_ways')->where('store_id', $store_id)->select('company')->distinct()->get();
            foreach($pay_ways as $k=>$v){
                if($v->company=='wftpay'){
                    $company_name='徽商银行';
                }else if($v->company=='wingpay'){
                    $company_name='翼支付';
                }else if($v->company=='vbill'){
                    $company_name='随行付';
                }else if($v->company=='alipay'){
                    $company_name='支付宝官方';
                }else if($v->company=='weixin'){
                    $company_name='微信官方';
                }else if($v->company=='hwcpay'){
                    $company_name='汇旺财';
                }else if($v->company=='nongjin'){
                    $company_name='农商行';
                }else if($v->company=='abc'){
                    $company_name='农行';
                }else if($v->company=='pingan'){
                    $company_name='平安银行';
                }else if($v->company=='jiujiang'){
                    $company_name='九江银行';
                }else if($v->company=='lianfuyoupay'){
                    $company_name='邮储银行';
                }else{
                    $company_name=$v->company;
                }
                $store_arr['company_name']=$company_name;
                $store_arr['store_id']=$store->store_id;
                
                $company_ways=DB::table('store_ways_desc')->where('company', $v->company)->select('ways_type as receive_code')->get();
                $company_ways=json_decode($company_ways,true);
                unset($pluckArray);
                foreach ($company_ways as $key1=>$val1){
                    $pluckArray[$key1]=$val1['receive_code'];
                }
                // 总金额
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $store_amount_company=0;
                    foreach ($ways_amount->get() as $obj) {
                        $store_amount_company += $obj->order_amount;
                    }
                    $store_amount_company=$store_amount_company/100;
                    
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount_zong->unionAll($refund_amount1);
                    $refund_amount_company=0;
                    foreach ($refund_amount_zong->get() as $obj) {
                        $refund_amount_company += $obj->refund_amount;
                    }
                    $refund_amount_company=$refund_amount_company/100;
                    
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong->unionAll($order_total_zong1);
                    $order_total=0;
                    foreach ($order_total_zong->get() as $obj) {
                        $order_total += $obj->order_total;
                    }
                    
                    $receive_fee_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong->unionAll($receive_fee_zong1);
                    $receive_fee=0;
                    foreach ($receive_fee_zong->get() as $obj) {
                        $receive_fee += $obj->receive_fee;
                    }
                    $receive_fee=$receive_fee/100;
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $store_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
                    $order_total=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_total')->sum('order_total');
                    $receive_fee=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('receive_fee')->sum('receive_fee')/100;
                }
                $store_arr['total_amount']=$store_amount_company;
                $store_arr['total_num']=$order_total;
                if(count($p_store_data)>100){
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }else{
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }
                $store_arr['commission_money']= $company_day_commission;
                $store_arr['fee_amount']=$receive_fee;
                $store_arr['refund_amount']=$refund_amount_company;
                $store_arr_data[]=$store_arr;
            }
            array_multisort( array_column($store_arr_data, 'total_amount'), SORT_DESC, $store_arr_data );
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
                'store_name'=>$store->store_name,
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'time'=>$start_data . '-' . $end_data
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }
    }
    
    public function sub_commission_store_company(Request $request){
        $format = [];
        $curHdIndex = $request->get('curHdIndex', '');
        $store_id = $request->get('store_id', '');
        $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
        $date_start = $request->get('start_date', '');
        $date_end = $request->get('end_date', '');
        try {
            switch (intval($curHdIndex)) {
                case 1://今日
                    $date_start = date('Y-m-d 00:00:00');
                    $date_end = date('Y-m-d 23:59:59');
                    break;
                case 2://昨日
                    $date_start = date('Y-m-d 00:00:00', strtotime("-1 day"));
                    $date_end = date('Y-m-d 23:59:59', strtotime("-1 day"));
                    break;
                case 3://上周
                    $date_start = date('Y-m-d 00:00:00', strtotime('last week'));
                    $date_end = date('Y-m-d 23:59:59', strtotime('this week -1 day'));
                    break;
                case 4://本月
                    $date_start = date('Y-m-01 00:00:00');
                    $date_end = date('Y-m-t 23:59:59');
                    break;
                case 5://上月
                    $date_start = date('Y-m-01 00:00:00', strtotime('-1 month', time()));
                    $date_end = date('Y-m-t 23:59:59', strtotime('-1 month', time()));
                    break;
            }
            $time_end = strtotime($date_end);
            $time_start = strtotime($date_start);
            if ($time_end<$date_start){
                throw new \Exception("结束时间不能大于开始时间");
            }
            if ($time_start<strtotime('2023-06-01')){
                throw new \Exception("查询最小时间不能低于2023-06-01");
            }
            if ($time_end>strtotime(date('Y-m-t 23:59:59'))){
                throw new \Exception("查询最大时间不能高于当天");
            }
            $db = DB::connection();

            $fee_amount = '0.00';
            $total_amount = '0.00';
            $refund_amount = '0.00';
            $commission_money = '0.00';

            $user_id = $request['user_id'];
            $store_rates = $db->table('store_pay_ways')->where('store_id', $store_id)->groupBy('company')->pluck(DB::raw("GROUP_CONCAT(ways_type)"), 'company')->toArray();
            $user_rates = $db->table('user_rates')->where('user_id', $user_id)->distinct('company')->pluck(DB::raw("CONCAT(server_rate,':',era_rate,':',rate,':',yu_rate)"), 'company')->toArray();
            $company_list = $db->table('store_all_pay_way_lists')->whereIn('company', array_keys(array_merge($store_rates,$user_rates)))->pluck('company_desc', 'company')->toArray();

            $merchant_list = [];
            if (is_array($store_rates)) {
                $monthTotal = $this->getMonthDifference(strtotime($date_start), strtotime($date_end));

                foreach ($store_rates as $company => $ways_type) {
                    $company_amount = '0.00';
                    $company_total = 0;
                    $company_refund = '0.00';
                    $company_fee = '0.00';
                    $company_commission = '0.00';
                    $company_name = $company_list[$company];
                    $company_rates = explode(':', $user_rates[$company]);
                    $explode = explode(',', $ways_type);
                    $tableName = 'wft_stores_orders_' . date('Ym', strtotime($date_start)) . '_bill';
                    $pluck = DB::connection('old_mysql')->table($tableName)
                        ->where('store_id', $store_id)
                        ->whereIn('receive_code', $explode)
                        ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                        ->select([
                            'receive_rate',
                            'receive_model',
                            DB::raw('sum(receive_fee) as receive_fee'),
                            DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                            DB::raw('sum(order_total) as order_total'),
                            DB::raw('sum(order_amount) as order_amount'),
                            DB::raw('sum(refund_total) as refund_total'),
                            DB::raw('sum(refund_amount) as refund_amount'),
                        ])
                        ->groupBy(Db::raw('receive_rate,receive_model'));
                    for ($i = 0; $i < $monthTotal; $i++) {
                        $num = $i + 1;
                        $numTime = strtotime("+" . $num . " month", strtotime($date_start));
                        $tableName = 'wft_stores_orders_' . date('Ym', $numTime) . '_bill';
                        $union_pluck = DB::connection('old_mysql')->table($tableName)
                            ->where('store_id', $store_id)
                            ->whereIn('receive_code', $explode)
                            ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                            ->select([
                                'receive_rate',
                                'receive_model',
                                DB::raw('sum(receive_fee) as receive_fee'),
                                DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                                DB::raw('sum(order_total) as order_total'),
                                DB::raw('sum(order_amount) as order_amount'),
                                DB::raw('sum(refund_total) as refund_total'),
                                DB::raw('sum(refund_amount) as refund_amount'),
                            ])
                            ->groupBy(Db::raw('receive_rate,receive_model'));
                        $pluck->unionAll($union_pluck);
                    }
                    foreach ($pluck->get() as $obj) {
                        $item = (array)$obj;
                        $user_rate = $company_rates[$item['receive_model'] - 1];
//                        if ($user_rate > 0 && $item['receive_rate'] > $user_rate) {
                            $difference = bcmul(bcdiv(bcsub($item['receive_rate'], $user_rate, 2), 100, 4), bcsub($item['order_amount'], $item['refund_amount']), 2);
                            $difference = bcdiv($difference, 100, 2);
                            $company_commission = bcadd($company_commission, $difference, 2);
//                        }
                        $company_amount = bcadd($company_amount, bcdiv($item['order_amount'], 100, 2), 2);
                        $company_total = bcadd($company_total, $item['order_total']);
                        $company_refund = bcadd($company_refund, bcdiv($item['refund_amount'], 100, 2), 2);
                        $company_fee = bcadd($company_fee, bcdiv($item['receive_fee'] - $item['receive_refund_fee'], 100, 2), 2);
                    }
                    $merchant_list[] = [
                        'company_name' => $company_name,
                        'total_amount' => $company_amount,
                        'total_num' => $company_total,
                        'refund_amount' => $company_refund,
                        'fee_amount' => $company_fee,
                        'commission_money' => $company_commission,
                    ];
                    $total_amount = bcadd($total_amount, $company_amount, 2);
                    $refund_amount = bcadd($refund_amount, $company_refund, 2);
                    $fee_amount = bcadd($fee_amount, $company_fee, 2);
                    $commission_money = bcadd($commission_money, $company_commission, 2);
                }
            }
            $format = [
                'total_amount' => bcsub($total_amount,$refund_amount,2),
                'total_commission' => $commission_money,
                'total_fee' => $fee_amount,
                'refund_amount' => $refund_amount,
                'store_company' => $merchant_list,
                'store_name'=> DB::table('stores')->where('store_id',$store_id)->value('store_name'),
                'start_date' => $date_start,
                'end_date' => $date_end,
                'time' => implode(' - ', [$date_start, $date_end])
            ];
            $this->status = 1;
            $this->message = 'Ok';
        } catch (\Exception $e) {
            $this->status = 2;
            $this->message = $e->getMessage();
        }
        return $this->format($format);
    }
    
    public function _sub_commission_store_company(Request $request){
        $token = $this->parseToken();
        $token_user_id = $request['user_id'];
        $login_user = User::where('id', $token_user_id)->where('is_delete', '=', '0')->first();
        if (!$login_user) {
            $this->status = '2';
            $this->message = '当前登录状态异常';
            return $this->format();
        }
        $curHdIndex = $request->get('curHdIndex', '');
        $store_id = $request->get('store_id', '');
        $store = DB::table('stores')->where('store_id', $store_id)->select('store_id','store_name','id')->first();
        $p_stores = DB::table('stores')->where('pid',$store->id)->select('store_id')->get();
//        print_r($p_stores);die;
        if(!empty($p_stores[0]->store_id)){
            $p_store_data[0]=$store->store_id;
            $p_stores=json_decode($p_stores,true);
            foreach($p_stores as $k1=>$v1){
                $p_store_data[]=$v1['store_id'];
            }
        }else{
            $p_store_data[0]=$store->store_id;
        }
        if($curHdIndex==1){
            $where[] = ['created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
            $where[] = ['created_at', '<=', date('Y-m-d', time()).' 23:59:59'];
            $start_date=date('Y-m-d', time());
            $end_date=date('Y-m-d', time());
            //总收款
            $total_amount=Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
            //总佣金
            $total_commission='待结算';
            $total_fee=Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('refund_amount')->sum('refund_amount');
            $pay_ways=DB::table('store_pay_ways')->where('store_id', $store_id)->select('company')->distinct()->get();
            foreach($pay_ways as $k=>$v){
                if($v->company=='wftpay'){
                    $company_name='徽商银行';
                }else if($v->company=='wingpay'){
                    $company_name='翼支付';
                }else if($v->company=='vbill'){
                    $company_name='随行付';
                }else if($v->company=='alipay'){
                    $company_name='支付宝官方';
                }else if($v->company=='weixin'){
                    $company_name='微信官方';
                }else if($v->company=='hwcpay'){
                    $company_name='汇旺财';
                }else if($v->company=='nongjin'){
                    $company_name='农商行';
                }else if($v->company=='abc'){
                    $company_name='农行';
                }else if($v->company=='pingan'){
                    $company_name='平安银行';
                }else if($v->company=='lianfuyoupay'){
                    $company_name='邮储银行';
                }else if($v->company=='jiujiang'){
                    $company_name='九江银行';
                }else{
                    $company_name=$v->company;
                }
                $store_arr['company_name']=$company_name;
                $store_arr['store_id']=$store->store_id;
                $store_arr['total_amount']=Order::whereIn('store_id', $p_store_data)->where($where)->where('company',$v->company)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
                $store_arr['total_num']=Order::whereIn('store_id', $p_store_data)->where($where)->where('company',$v->company)->whereIn('pay_status', [1, 6])->select('total_amount')->count('total_amount');
                $store_arr['refund_amount']=Order::whereIn('store_id', $p_store_data)->where($where)->where('company',$v->company)->whereIn('pay_status', [1, 6])->select('refund_amount')->sum('refund_amount');
                $store_arr['fee_amount']=Order::whereIn('store_id', $p_store_data)->where($where)->where('company',$v->company)->whereIn('pay_status', [1, 6])->select('fee_amount')->sum('fee_amount');
                $store_arr['commission_money']='待结算';
                $store_arr_data[]=$store_arr;
            }
            array_multisort( array_column($store_arr_data, 'total_amount'), SORT_DESC, $store_arr_data );
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
                'store_name'=>$store->store_name,
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'time'=>date('Y-m-d', time()).' 00:00:00'.'-'.date('Y-m-d', time()).' 23:59:59'
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex==2){
            $where[] = ['bill_date', '>=', strtotime('yesterday')];
            $where[] = ['bill_date', '<=', strtotime('yesterday')+86399];
            $where_c[] = ['settling_day', '>=', date('Y-m-d',strtotime("-1 day"))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d',strtotime("-1 day"))];
            $start_date=date('Y-m-d',strtotime("-1 day"));
            $end_date=date('Y-m-d',strtotime("-1 day"));
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $store_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $store_amount += $obj->order_amount;
                }
                $store_amount=$store_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $store_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=$store_amount;
            //总佣金
            $get_commission=$start_date.','.$end_date;
            if(count($p_store_data)>100){
                $total_commission=DB::table('company_day_commission')->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }else{
                $total_commission=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }
            $total_fee=$refund_amount;
            $pay_ways=DB::table('store_pay_ways')->where('store_id', $store_id)->select('company')->distinct()->get();
            foreach($pay_ways as $k=>$v){
                if($v->company=='wftpay'){
                    $company_name='徽商银行';
                }else if($v->company=='wingpay'){
                    $company_name='翼支付';
                }else if($v->company=='vbill'){
                    $company_name='随行付';
                }else if($v->company=='alipay'){
                    $company_name='支付宝官方';
                }else if($v->company=='weixin'){
                    $company_name='微信官方';
                }else if($v->company=='hwcpay'){
                    $company_name='汇旺财';
                }else if($v->company=='nongjin'){
                    $company_name='农商行';
                }else if($v->company=='abc'){
                    $company_name='农行';
                }else if($v->company=='pingan'){
                    $company_name='平安银行';
                }else if($v->company=='lianfuyoupay'){
                    $company_name='邮储银行';
                }else if($v->company=='lianfuyoupay'){
                    $company_name='邮储银行';
                }else if($v->company=='jiujiang'){
                    $company_name='九江银行';
                }else{
                    $company_name=$v->company;
                }
                $store_arr['company_name']=$company_name;
                $store_arr['store_id']=$store->store_id;
                
                $company_ways=DB::table('store_ways_desc')->where('company', $v->company)->select('ways_type as receive_code')->get();
                $company_ways=json_decode($company_ways,true);
                unset($pluckArray);
                foreach ($company_ways as $key1=>$val1){
                    $pluckArray[$key1]=$val1['receive_code'];
                }
                // 总金额
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $store_amount_company=0;
                    foreach ($ways_amount->get() as $obj) {
                        $store_amount_company += $obj->order_amount;
                    }
                    $store_amount_company=$store_amount_company/100;
                    
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount_zong->unionAll($refund_amount1);
                    $refund_amount_company=0;
                    foreach ($refund_amount_zong->get() as $obj) {
                        $refund_amount_company += $obj->refund_amount;
                    }
                    $refund_amount_company=$refund_amount_company/100;
                    
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong->unionAll($order_total_zong1);
                    $order_total=0;
                    foreach ($order_total_zong->get() as $obj) {
                        $order_total += $obj->order_total;
                    }
                    
                    $receive_fee_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong->unionAll($receive_fee_zong1);
                    $receive_fee=0;
                    foreach ($receive_fee_zong->get() as $obj) {
                        $receive_fee += $obj->receive_fee;
                    }
                    $receive_fee=$receive_fee/100;
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $store_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
                    $order_total=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_total')->sum('order_total');
                    $receive_fee=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('receive_fee')->sum('receive_fee')/100;
                }
                $store_arr['total_amount']=$store_amount_company;
                $store_arr['total_num']=$order_total;
                if(count($p_store_data)>100){
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }else{
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }
                $store_arr['commission_money']= $company_day_commission;
                $store_arr['fee_amount']=$receive_fee;
                $store_arr['refund_amount']=$refund_amount_company;
                $store_arr_data[]=$store_arr;
            }
            array_multisort( array_column($store_arr_data, 'total_amount'), SORT_DESC, $store_arr_data );
            
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
                'store_name'=>$store->store_name,
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'time'=>date('Y-m-d',strtotime("-1 day")).'-'.date('Y-m-d',strtotime("-1 day"))
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex==3){
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'))];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime('last week'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime('this week -1 day'))];
            $start_date=date('Y-m-d', strtotime('last week'));
            $end_date=date('Y-m-d', strtotime('this week -1 day'));
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $store_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $store_amount += $obj->order_amount;
                }
                $store_amount=$store_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $store_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=$store_amount;
            //总佣金
            $get_commission=$start_date.','.$end_date;
            if(count($p_store_data)>100){
                $total_commission=DB::table('company_day_commission')->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }else{
                $total_commission=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }
            $total_fee=$refund_amount;
            $pay_ways=DB::table('store_pay_ways')->where('store_id', $store_id)->select('company')->distinct()->get();
            foreach($pay_ways as $k=>$v){
                if($v->company=='wftpay'){
                    $company_name='徽商银行';
                }else if($v->company=='wingpay'){
                    $company_name='翼支付';
                }else if($v->company=='vbill'){
                    $company_name='随行付';
                }else if($v->company=='alipay'){
                    $company_name='支付宝官方';
                }else if($v->company=='weixin'){
                    $company_name='微信官方';
                }else if($v->company=='hwcpay'){
                    $company_name='汇旺财';
                }else if($v->company=='nongjin'){
                    $company_name='农商行';
                }else if($v->company=='abc'){
                    $company_name='农行';
                }else if($v->company=='pingan'){
                    $company_name='平安银行';
                }else if($v->company=='lianfuyoupay'){
                    $company_name='邮储银行';
                }else if($v->company=='jiujiang'){
                    $company_name='九江银行';
                }else{
                    $company_name=$v->company;
                }
                $store_arr['company_name']=$company_name;
                $store_arr['store_id']=$store->store_id;
                
                $company_ways=DB::table('store_ways_desc')->where('company', $v->company)->select('ways_type as receive_code')->get();
                $company_ways=json_decode($company_ways,true);
                unset($pluckArray);
                foreach ($company_ways as $key1=>$val1){
                    $pluckArray[$key1]=$val1['receive_code'];
                }
                // 总金额
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $store_amount_company=0;
                    foreach ($ways_amount->get() as $obj) {
                        $store_amount_company += $obj->order_amount;
                    }
                    $store_amount_company=$store_amount_company/100;
                    
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount_zong->unionAll($refund_amount1);
                    $refund_amount_company=0;
                    foreach ($refund_amount_zong->get() as $obj) {
                        $refund_amount_company += $obj->refund_amount;
                    }
                    $refund_amount_company=$refund_amount_company/100;
                    
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong->unionAll($order_total_zong1);
                    $order_total=0;
                    foreach ($order_total_zong->get() as $obj) {
                        $order_total += $obj->order_total;
                    }
                    
                    $receive_fee_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong->unionAll($receive_fee_zong1);
                    $receive_fee=0;
                    foreach ($receive_fee_zong->get() as $obj) {
                        $receive_fee += $obj->receive_fee;
                    }
                    $receive_fee=$receive_fee/100;
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $store_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
                    $order_total=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_total')->sum('order_total');
                    $receive_fee=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('receive_fee')->sum('receive_fee')/100;
                }
                $store_arr['total_amount']=$store_amount_company;
                $store_arr['total_num']=$order_total;
                if(count($p_store_data)>100){
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }else{
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }
                $store_arr['commission_money']= $company_day_commission;
                $store_arr['fee_amount']=$receive_fee;
                $store_arr['refund_amount']=$refund_amount_company;
                $store_arr_data[]=$store_arr;
            }
            array_multisort( array_column($store_arr_data, 'total_amount'), SORT_DESC, $store_arr_data );
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
                'store_name'=>$store->store_name,
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'time'=>date('Y-m-d', strtotime('last week')).'-'.date('Y-m-d', strtotime('this week -1 day'))
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex==4){
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),1,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(0,0,0,date('m'),date('d'),date('Y'))-1];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d',strtotime("-1 day"))];
            $start_date=date('Y-m-d', strtotime('last week'));
            $end_date=date('Y-m-d', strtotime('this week -1 day'));
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $store_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $store_amount += $obj->order_amount;
                }
                $store_amount=$store_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $store_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=$store_amount;
            //总佣金
            $get_commission=$start_date.','.$end_date;
            if(count($p_store_data)>100){
                $total_commission=DB::table('company_day_commission')->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }else{
                $total_commission=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }
            $total_fee=$refund_amount;
            $pay_ways=DB::table('store_pay_ways')->where('store_id', $store_id)->select('company')->distinct()->get();
            foreach($pay_ways as $k=>$v){
                if($v->company=='wftpay'){
                    $company_name='徽商银行';
                }else if($v->company=='wingpay'){
                    $company_name='翼支付';
                }else if($v->company=='vbill'){
                    $company_name='随行付';
                }else if($v->company=='alipay'){
                    $company_name='支付宝官方';
                }else if($v->company=='weixin'){
                    $company_name='微信官方';
                }else if($v->company=='hwcpay'){
                    $company_name='汇旺财';
                }else if($v->company=='nongjin'){
                    $company_name='农商行';
                }else if($v->company=='abc'){
                    $company_name='农行';
                }else if($v->company=='pingan'){
                    $company_name='平安银行';
                }else if($v->company=='lianfuyoupay'){
                    $company_name='邮储银行';
                }else if($v->company=='jiujiang'){
                    $company_name='九江银行';
                }else{
                    $company_name=$v->company;
                }
                $store_arr['company_name']=$company_name;
                $store_arr['store_id']=$store->store_id;
                
                $company_ways=DB::table('store_ways_desc')->where('company', $v->company)->select('ways_type as receive_code')->get();
                $company_ways=json_decode($company_ways,true);
                unset($pluckArray);
                foreach ($company_ways as $key1=>$val1){
                    $pluckArray[$key1]=$val1['receive_code'];
                }
                // 总金额
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $store_amount_company=0;
                    foreach ($ways_amount->get() as $obj) {
                        $store_amount_company += $obj->order_amount;
                    }
                    $store_amount_company=$store_amount_company/100;
                    
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount_zong->unionAll($refund_amount1);
                    $refund_amount_company=0;
                    foreach ($refund_amount_zong->get() as $obj) {
                        $refund_amount_company += $obj->refund_amount;
                    }
                    $refund_amount_company=$refund_amount_company/100;
                    
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong->unionAll($order_total_zong1);
                    $order_total=0;
                    foreach ($order_total_zong->get() as $obj) {
                        $order_total += $obj->order_total;
                    }
                    
                    $receive_fee_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong->unionAll($receive_fee_zong1);
                    $receive_fee=0;
                    foreach ($receive_fee_zong->get() as $obj) {
                        $receive_fee += $obj->receive_fee;
                    }
                    $receive_fee=$receive_fee/100;
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $store_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
                    $order_total=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_total')->sum('order_total');
                    $receive_fee=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('receive_fee')->sum('receive_fee')/100;
                }
                $store_arr['total_amount']=$store_amount_company;
                $store_arr['total_num']=$order_total;
                if(count($p_store_data)>100){
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }else{
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }
                $store_arr['commission_money']= $company_day_commission;
                $store_arr['fee_amount']=$receive_fee;
                $store_arr['refund_amount']=$refund_amount_company;
                $store_arr_data[]=$store_arr;
            }
            array_multisort( array_column($store_arr_data, 'total_amount'), SORT_DESC, $store_arr_data );
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
                'store_name'=>$store->store_name,
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'time'=>date('Y-m-d', strtotime('last week')).'-'.date('Y-m-d', strtotime('this week -1 day'))
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex==5){
            $where[] = ['bill_date', '>=', strtotime(date('Y-m-01 00:00:00',strtotime(date('Y-m-01') . " - 1 month")))];
            $where[] = ['bill_date', '<=', strtotime(date("Y-m-d 23:59:59", strtotime(-date('d').'day')))];
            $where_c[] = ['settling_day', '>=', date('Y-m-01', strtotime('-1 month'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-t', strtotime('-1 month'))];
            $start_date=date('Y-m-01', strtotime(date('Y-m-01') . " - 1 month"));
            $end_date=date('Y-m-t', strtotime('-1 month'));
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $store_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $store_amount += $obj->order_amount;
                }
                $store_amount=$store_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $store_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
            }
            
            $total_amount=$store_amount;
            //总佣金
            $get_commission=$start_date.','.$end_date;
            if(count($p_store_data)>100){
                $total_commission=DB::table('company_day_commission')->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }else{
                $total_commission=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
            }
            $total_fee=$refund_amount;
            $pay_ways=DB::table('store_pay_ways')->where('store_id', $store_id)->select('company')->distinct()->get();
            foreach($pay_ways as $k=>$v){
                if($v->company=='wftpay'){
                    $company_name='徽商银行';
                }else if($v->company=='wingpay'){
                    $company_name='翼支付';
                }else if($v->company=='vbill'){
                    $company_name='随行付';
                }else if($v->company=='alipay'){
                    $company_name='支付宝官方';
                }else if($v->company=='weixin'){
                    $company_name='微信官方';
                }else if($v->company=='hwcpay'){
                    $company_name='汇旺财';
                }else if($v->company=='nongjin'){
                    $company_name='农商行';
                }else if($v->company=='abc'){
                    $company_name='农行';
                }else if($v->company=='pingan'){
                    $company_name='平安银行';
                }else if($v->company=='lianfuyoupay'){
                    $company_name='邮储银行';
                }else if($v->company=='jiujiang'){
                    $company_name='九江银行';
                }else{
                    $company_name=$v->company;
                }
                $store_arr['company_name']=$company_name;
                $store_arr['store_id']=$store->store_id;
                
                $company_ways=DB::table('store_ways_desc')->where('company', $v->company)->select('ways_type as receive_code')->get();
                $company_ways=json_decode($company_ways,true);
                unset($pluckArray);
                foreach ($company_ways as $key1=>$val1){
                    $pluckArray[$key1]=$val1['receive_code'];
                }
                // 总金额
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $store_amount_company=0;
                    foreach ($ways_amount->get() as $obj) {
                        $store_amount_company += $obj->order_amount;
                    }
                    $store_amount_company=$store_amount_company/100;
                    
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['refund_amount']);
                    $refund_amount_zong->unionAll($refund_amount1);
                    $refund_amount_company=0;
                    foreach ($refund_amount_zong->get() as $obj) {
                        $refund_amount_company += $obj->refund_amount;
                    }
                    $refund_amount_company=$refund_amount_company/100;
                    
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['order_total']);
                    $order_total_zong->unionAll($order_total_zong1);
                    $order_total=0;
                    foreach ($order_total_zong->get() as $obj) {
                        $order_total += $obj->order_total;
                    }
                    
                    $receive_fee_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select(['receive_fee']);
                    $receive_fee_zong->unionAll($receive_fee_zong1);
                    $receive_fee=0;
                    foreach ($receive_fee_zong->get() as $obj) {
                        $receive_fee += $obj->receive_fee;
                    }
                    $receive_fee=$receive_fee/100;
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $store_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
                    $order_total=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('order_total')->sum('order_total');
                    $receive_fee=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->where('store_id',$store_id)->select('receive_fee')->sum('receive_fee')/100;
                }
                $store_arr['total_amount']=$store_amount_company;
                $store_arr['total_num']=$order_total;
                if(count($p_store_data)>100){
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }else{
                    $company_day_commission=DB::table('company_day_commission')->where('company',$v->company)->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money'); //总佣金
                }
                $store_arr['commission_money']= $company_day_commission;
                $store_arr['fee_amount']=$receive_fee;
                $store_arr['refund_amount']=$refund_amount_company;
                $store_arr_data[]=$store_arr;
            }
            array_multisort( array_column($store_arr_data, 'total_amount'), SORT_DESC, $store_arr_data );
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_company'=>$store_arr_data,
                'store_name'=>$store->store_name,
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'time'=>date('Y-m-d', strtotime('last week')).'-'.date('Y-m-d', strtotime('this week -1 day'))
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }
    }

//    //获取代理默认通道
//    public function get_user_company(Request $request){
//        $token = $this->parseToken();
//        $token_user_id = $token->user_id;
//        $pay_ways=DB::table('user_rates')->where('user_id', $token_user_id)->select('company')->distinct()->get();
//        foreach($pay_ways as $k=>$v){
//            $ways[$k]['company']=$v->company;
//            if($v->company=='vbill'){
//                $ways[$k]['company_name']='随行付';
//            }else if($v->company=='wftpay'){
//                $ways[$k]['company_name']='徽商银行';
//            }else if($v->company=='wingpay'){
//                $ways[$k]['company_name']='翼支付';
//            }
//        }
//        $this->status = '1';
//        $this->message = '数据返回成功';
//        return $this->format($ways);
//    }

    //获取俩时间间隔日期
    public function getDateFromRange($startdate, $enddate){

        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);

        // 计算日期段内有多少天
        $days = ($etimestamp-$stimestamp)/86400+1;

        // 保存每天日期
        $date = array();

        for($i=0; $i<$days; $i++){
            $date[] = date('Y-m-d', $stimestamp+(86400*$i));
        }

        return $date;
    }


    // 首付科技-分润账单列表
    public function sf_commission_lists(Request $request)
    {
        try {
            $token = $this->parseToken();
            $token_user_id = $token->user_id;

            $time = $request->get('time_start', '');
            $user_id = $request->get('user_id', '');  //服务商id
            $amount_start = $request->get('amount_start', '');
            $amount_end = $request->get('amount_end', '');

            $login_user = User::where('id', $token_user_id)
                ->where('is_delete', '=', '0')
                ->first();
            if (!$login_user) {
                $this->status = '2';
                $this->message = '当前登录状态异常';
                return $this->format();
            }
            if ($login_user->level != '0') {
                $this->status = '3';
                $this->message = '非平台账户无此全权';
                return $this->format();
            }

            $re_data = [
                'time_start' => $time,
            ];
            $check_data = [
                'time_start' => '交易时间',
            ];
            $check = $this->check_required($re_data, $check_data);
            if ($check) {
                $this->status = '2';
                $this->message = $check;
                return $this->format();
            }

            $time_arr = explode('-', $time);
            $year = $time_arr[0];
            $month = $time_arr[1];
            $month_day = date('t', strtotime($time));
            $start_time = date('Y-m-d H:i:s', mktime(0,0,0,$month,1,$year));
            $end_time = date('Y-m-d H:i:s', mktime(23,59,59,$month,$month_day,$year));

            if (isset($user_id) && ($user_id != 'undefined') && $user_id) {
                $user_ids = $this->getSubIds($user_id);
            } else {
                $user_ids = $this->getSubIds($token_user_id);
            }

            $where = [];
            if ($amount_start) {
                $where[] = ['total_amount', '>=', "$amount_start"];
            }
            if ($amount_end) {
                $where[] = ['total_amount', '<=', "$amount_end"];
            }
            if (1) {
                $where[] = ['ways_type', '!=', '2005'];
            }

            if (env('DB_DATABASE_FIRSTPAY')) {
                $db = DB::connection('mysql_firstpay'); //连接首付科技数据库
            } else {
                $this->status = '3';
                $this->message = '首付科技数据库连接异常';
                return $this->format();
            }

            $obj = $db->table('orders')->select([
                DB::raw("date_format(pay_time, '%Y-%m-%d') AS `modify_pay_time`"),
                'store_name',
                'company',
                'rate',
                'cost_rate',  //成本费率
                'ways_source_desc',
                DB::raw("SUM(`total_amount`) AS `total_amount_sum`"),
                DB::raw("SUM(`mdiscount_amount`) AS `mdiscount_amount_sum`"),
                DB::raw("SUM(IF((`pay_status`=1), `total_amount`, 0)) as `total_success_amount`"),
                DB::raw("SUM(IF((`pay_status`=6), `total_amount`, 0)) as `total_return_amount`"),
                'pay_status_desc',
                DB::raw("COUNT(`total_amount`) as `total_amount_count`"),
                'refund_amount' //分润金额
            ])
                ->where($where)
                ->where('pay_time', '>=', "$start_time")
                ->where('pay_time', '<=', "$end_time")
                ->where('pay_status_desc', '<>', '会员卡支付成功')
                ->where('company', '<>', 'alipay')
                ->where('company', '<>', 'weixin')
                ->whereIn('pay_status', ['1', '6'])
                ->whereIn('user_id', $user_ids)
                ->groupBy(['modify_pay_time', 'store_id', 'company', 'rate', 'ways_source', 'pay_status'])
                ->orderBy('modify_pay_time', 'asc');

            $this->t = count($obj->get()->toArray());
            $data = $this->page($obj)->get();
//            $this->order_data = [
//                'login_level' => $login_user->level,
//                'total_money' => number_format($total_money, 2),
//                'total_number' => $total_number,
//                'total_profit' => ,
//            ];
        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage().'-'.$exception->getLine();
            return $this->format();
        }

        $this->status = '1';
        $this->message = '数据返回成功';
        return $this->format($data);
    }


}